Inserted value is not visible to the second query - c#

There are two tables customer_invoice and sold_item_details
in customer_invoice table there is column, cus_inv_id (PK)
This cus_inv_id is a foreign key to the sold_item_details
Here is my abstract view of the code,
public void txtRent_PreviewKeyDown(object sender, KeyEventArgs e){
/* This method will Insert values to the customer_invoice table */
CreateOrder();
/* This method will Insert values to the sold_item_details table*/
InsertOrderItem(OrderItem orderItem);
}
Here is my question when insertion query is executed the second query raise a MysqlException of Cannot add or update a child row. I checked in between CreateOrder() and InserOrderItem() whether the insertion process has completed surprisingly it turns out it has succeeded.
for example if i insert value set with cus_inv_id = 1 it will be inserted to the table customer_invoice but when inserting to the sold_item_details table with cus_inv_id (FK) = 1 it raise that exception.
These are the two codes related to those two methods. (I have removed some columns for the ease of the problem)
public void CreateOrder()
{
_connection.open();
var mysqlTrans = _connection.BeginTransaction();
var orderId = -1;
MySqlDataReader sqlDataReader;
try
{
const string query =
"SELECT cus_inv_id FROM customer_invoice " +
"WHERE customer_id = #cusId";
var mysqlCommand1 = new MySqlCommand(query, _connection, mysqlTrans);
mysqlCommand1.Parameters.AddWithValue("#cusId", customerId);
sqlDataReader = mysqlCommand1.ExecuteReader();
if (sqlDataReader.HasRows)
{
sqlDataReader.Read();
orderId = (int) sqlDataReader["cus_inv_id"];
}
sqlDataReader.Close();
if (orderId == -1)
{
var mysqlCommand2 = _connection.CreateCommand();
mysqlCommand2.Connection = _connection;
mysqlCommand2.Transaction = mysqlTrans;
mysqlCommand2.CommandText = "SELECT MAX(cus_inv_id) FROM customer_invoice " +
"HAVING MAX(cus_inv_id) IS NOT NULL";
sqlDataReader = mysqlCommand2.ExecuteReader();
if (sqlDataReader.Read())
{
orderId = (int) sqlDataReader["MAX(cus_inv_id)"] + 1;
}
else
{
orderId += 2;
}
sqlDataReader.Close();
mysqlCommand2.CommandText =
"INSERT INTO customer_invoice(cus_inv_id)" +
" VALUES(#cusInvId)";
mysqlCommand2.Parameters.AddWithValue("#cusInvId", orderId);
mysqlCommand2.ExecuteNonQuery();
}
mysqlTrans.Commit();
_connection.close();
}
catch (Exception ex)
{
MessageBox.Show(ex);
mysqlTrans.Rollback();
}
}
public void InsertOrderItem(OrderItem orderItem)
{
_connection.open();
var mysqlCommand = _connection.CreateCommand();
var mysqlTrans = _connection.BeginTransaction();
mysqlCommand.Connection = _connection;
mysqlCommand.Transaction = mysqlTrans;
try
{
mysqlCommand.CommandText = "SELECT MAX(sold_item_id) FROM sold_item_details " +
"HAVING MAX(sold_item_id) IS NOT NULL";
var sqlDataReader = mysqlCommand.ExecuteReader();
var lastSoldItemId = 1;
if (sqlDataReader.Read())
{
lastSoldItemId = (int) sqlDataReader["MAX(sold_item_id)"] +1;
}
sqlDataReader.Close();
mysqlCommand.CommandText = "INSERT INTO sold_item_details(sold_item_id,cus_inv_id) VALUES(#soldItemId, #cusInvId)";
mysqlCommand.Parameters.AddWithValue("#soldItemId", lastSoldItemId);
mysqlCommand.Parameters.AddWithValue("#cusInvId", orderItem.OrderId);
mysqlCommand.ExecuteNonQuery();
mysqlTrans.Commit();
_connection.close();
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
mysqlTrans.Rollback();
}
}

Related

No current row message appears while getting Max values from SQLite database

I want to get max value form database if database not empty. Program works fine but it gives No Current Row message on start. I've query like this,
public int GetMaxValue(String table, String column, int columnIndex)
{
try
{
int values = -1;
String query = "SELECT MAX(" + column + ") FROM " + table;
SQLiteCommand sQLiteCommand = new SQLiteCommand(query, sQLiteConnection);
sQLiteCommand.ExecuteNonQuery();
using (SQLiteDataReader sQLiteDataReader = sQLiteCommand.ExecuteReader())
{
if (!sQLiteDataReader.IsDBNull(0))
{
while (sQLiteDataReader.Read())
{
values = sQLiteDataReader.GetInt32(columnIndex);
sQLiteDataReader.Close();
return values;
}
}
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
return -1;
}
and call this method by,
string orderNo = database.GetMaxValue(Database.TABLE_ORDER, Database.INVOICE_NO_ORDER, 0).ToString();
in above function, i've check already if Reader Null then do not continue by this,
if (!sQLiteDataReader.IsDBNull(0))
}
but its not works. Kindly tell how to get rid of No Current Row message
This solve my problem
public Int32 GetMaxValue(String table, String column, int columnIndex)
{
try
{
Int32 values = -1;
String query = "SELECT MAX(" + column + ") FROM " + table;
SQLiteCommand sQLiteCommand = new SQLiteCommand(query, sQLiteConnection);
sQLiteCommand.ExecuteScalar();
using (SQLiteDataReader sQLiteDataReader = sQLiteCommand.ExecuteReader())
{
if (sQLiteDataReader.Read())
{
while (sQLiteDataReader.Read())
{
values = sQLiteDataReader.GetInt32(columnIndex);
return values;
}
}
sQLiteDataReader.Close();
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
return -1;
}

ProductInsert() does not exist in current context

protected void Btn_CheckOut_Click(object sender, EventArgs e)
{
int result = 0;
Payment user = new Payment(txt_CardNumber.Text, txt_CardHolderName.Text, txt_ExpirationDate.Text, txt_Cvv.Text);
result = ProductInsert();
/* Session["CardNumber"] = txt_CardNumber.Text;
Session["CardHolderName"] = txt_CardHolderName.Text;
Session["ExpirationDate"] = txt_ExpirationDate.Text;
Session["Cvv"] = txt_Cvv.Text;*/
Response.Redirect("Payment Sucessful.aspx");
}
public int ProductInsert()
{
int result = 0;
string queryStr = "INSERT INTO CustomerDetails(CardNumber, CardHolderName, ExpirationDate, Cvv)"
+ "values (#CardNumber,#CardHolderName, #ExpirationDate, #Cvv)";
try
{
SqlConnection conn = new SqlConnection(connStr);
SqlCommand cmd = new SqlCommand(queryStr, conn);
cmd.Parameters.AddWithValue("#CardNumber", this.CardNumber);
cmd.Parameters.AddWithValue("#CardHolderName", this.CardHolderName);
cmd.Parameters.AddWithValue("#ExpirationDate", this.ExpirationDate);
cmd.Parameters.AddWithValue("#Cvv", this.Cvv);
conn.Open();
result += cmd.ExecuteNonQuery(); // Returns no. of rows affected. Must be > 0
conn.Close();
return result;
}
catch (Exception ex)
{
return 0;
}
}
}
I am trying to store credit card informations into database. I have created a productInsert() method and now I am trying to insert whatever values into the database.
This code is giving the error:
ProductInsert() does not exist in current context

How to update datagridview if I add new row to existing rows in C#?

In my program which has datagridview for insert,update or delete Purchase Order and it behave like as a shopping cart.This datagridview consist of BookName,ISBNNo,Order quantity,unit price and total.When I insert this datagridview data to database,each row insert with unique id PO_Cart_No(pk) which has identity value.
And also other background textbox details which are Po_No,supplier_Id and Grand total details insert into separate table which called PO table.And also this two tables link with foreign key PO_No.My question is when I add new row to existing row to update database,that new row didn't insert and other row data has updated.
Where is the problem.This is my code for you,
public void UpdatePurchseOrderTable(int PO_No,int Supplier_ID, string Date, string RequiredDate, double GrandTotal)
{
DynamicConnection con = new DynamicConnection();
con.mysqlconnection();
string query = "UPDATE TBL_PO "
+ " SET Supplier_ID = #Supplier_ID,Date = #Date,"
+ "RequiredDate = #RequiredDate,GrandTotal=#GrandTotal"
+ " WHERE PO_No = #PO_No";
con.sqlquery(query);
con.cmd.Parameters.Add(new SqlParameter("#PO_No", SqlDbType.Int));
con.cmd.Parameters["#PO_No"].Value = PO_No;
con.cmd.Parameters.Add(new SqlParameter("#Supplier_ID", SqlDbType.Int));
con.cmd.Parameters["#Supplier_ID"].Value = Supplier_ID;
con.cmd.Parameters.Add(new SqlParameter("#Date", SqlDbType.Date));
con.cmd.Parameters["#Date"].Value = Date;
con.cmd.Parameters.Add(new SqlParameter("#RequiredDate", SqlDbType.Date));
con.cmd.Parameters["#RequiredDate"].Value = RequiredDate;
con.cmd.Parameters.Add(new SqlParameter("#GrandTotal", SqlDbType.Money));
con.cmd.Parameters["#GrandTotal"].Value = GrandTotal;
con.nonquery();
}
public void UpdatePOCartTable(int PO_No,string ISBN_No,int OrderQuantity, double UnitPrice, double Total)
{
DynamicConnection con = new DynamicConnection();
con.mysqlconnection();
string query = "UPDATE TBL_PO_Cart"
+ " SET ISBN_No = #ISBN_No, OrderQuantity= #OrderQuantity,"
+ "UnitPrice= #UnitPrice,Total=#Total"
+ " WHERE PO_No = #PO_No";
con.sqlquery(query);
con.cmd.Parameters.Add(new SqlParameter("#PO_No", SqlDbType.Int));
con.cmd.Parameters["#PO_No"].Value = PO_No;
con.cmd.Parameters.Add(new SqlParameter("#ISBN_No", SqlDbType.NVarChar));
con.cmd.Parameters["#ISBN_No"].Value = ISBN_No;
con.cmd.Parameters.Add(new SqlParameter("#OrderQuantity", SqlDbType.NVarChar));
con.cmd.Parameters["#OrderQuantity"].Value = OrderQuantity;
con.cmd.Parameters.Add(new SqlParameter("#UnitPrice", SqlDbType.Money));
con.cmd.Parameters["#UnitPrice"].Value = Math.Round(UnitPrice,2,MidpointRounding.AwayFromZero);
con.cmd.Parameters.Add(new SqlParameter("#Total", SqlDbType.Money));
con.cmd.Parameters["#Total"].Value = Math.Round(Total,2,MidpointRounding.AwayFromZero);
con.nonquery();
}
and PO form data as follows
private void btnedit_Click(object sender, EventArgs e)
{
DynamicConnection con = new DynamicConnection();
try
{
if (txtPONo.Text != "" || cmbsupID.Text != "" || date1.Text != "" || requireddate.Text != "" || txtgrandTotal.Text != "")
{
PurchaseOrder PO = new PurchaseOrder();
if (cmbsupID.Text.Contains('-'))
{
string str = cmbsupID.Text;
int index = str.IndexOf('-');
if (index > 0)
{
int value = int.Parse(str.Substring(0, index));
PO.UpdatePurchseOrderTable(Convert.ToInt32(txtPONo.Text), value, date1.Text, requireddate.Text, Convert.ToDouble(txtgrandTotal.Text));
}
}
else
{
int value2 = Convert.ToInt32(cmbsupID.Text);
PO.UpdatePurchseOrderTable(Convert.ToInt32(txtPONo.Text), value2, date1.Text, requireddate.Text, Convert.ToDouble(txtgrandTotal.Text));
}
for (int i = 0; i < dataGridView1.Rows.Count-1; i++)
{
int PONO = Convert.ToInt32(txtPONo.Text);
string column1 = Convert.ToString(dataGridView1.Rows[i].Cells[1].Value);
int column2 = Convert.ToInt32(dataGridView1.Rows[i].Cells[2].Value);
double column3= Convert.ToDouble(dataGridView1.Rows[i].Cells[3].Value);
double column4 = Convert.ToDouble(dataGridView1.Rows[i].Cells[4].Value);
PO.UpdatePOCartTable(PONO,column1,column2,column3,column4);
}
}
else
{
MessageBox.Show("Please Provide Details!");
}
dataGridView1.Rows.Clear();
ClearData();
retviewPO_No();
MessageBox.Show("Record Updated Successfully");
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}

How to insert data into two SQL Server tables in asp.net

I have two tables, the first table is Course and this table contains three columns Course_ID, Name_of_course, DeptID; and the second table is Department and it has three columns DeptID, DepName, College.
I put a GridView to display the data that I will add it. But when I write the command to insert the data in both tables the data don't add. I used this command
protected void GridView1_SelectedIndexChanged(object sender, EventArgs e)
{
try
{
GridViewRow r = GridView1.SelectedRow;
Dbclass db = new Dbclass();
string s = "";
DataTable dt = db.getTable(s);
ddcollege.SelectedValue = dt.Rows[0]["College"].ToString();
dddept.SelectedValue = dt.Rows[1]["DepName"].ToString();
tbid.Text = r.Cells[0].Text;
tbcourse_name.Text = r.Cells[1].Text;
lblid.Text = tbid.Text;
lberr.Text = "";
}
catch (Exception ex)
{
lberr.Text = ex.Message;
}
}
protected void btadd_Click(object sender, EventArgs e)
{
try
{
if (tbid.Text == "")
{
lberr.Text = "Please input course id";
return;
}
if (tbcourse_name.Text == "")
{
lberr.Text = "Please input course name";
return;
}
string s = "Insert into Course(Course_ID,Name_of_course) values ('" + tbid.Text + "','" + tbcourse_name.Text + "')";
s = "INSERT INTO Department (DepName,College,DeptID) VALUES ('"+dddept.SelectedValue+"','"+ddcollege.SelectedValue+"','"+tbdeptID.Text+"')";
Dbclass db = new Dbclass();
if (db.Run(s))
{
lberr.Text = "The data is added";
lblid.Text = tbid.Text;
}
else
{
lberr.Text = "The data is not added";
}
SqlDataSource1.DataBind();
GridView1.DataBind();
}
catch (Exception ex)
{
lberr.Text = ex.Message;
}
}
Here is the Dbclass code:
public class Dbclass
{
SqlConnection dbconn = new SqlConnection();
public Dbclass()
{
try
{
dbconn.ConnectionString = #"Data Source=Fingerprint.mssql.somee.com;Initial Catalog=fingerprint;Persist Security Info=True;User ID=Fingerprint_SQLLogin_1;Password=********";
dbconn.Open();
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
}
//----- run insert, delete and update
public bool Run(String sql)
{
bool done= false;
try
{
SqlCommand cmd = new SqlCommand(sql,dbconn);
cmd.ExecuteNonQuery();
done= true;
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
return done;
}
//----- run insert, delete and update
public DataTable getTable(String sql)
{
DataTable done = null;
try
{
SqlDataAdapter da = new SqlDataAdapter(sql, dbconn);
DataSet ds = new DataSet();
da.Fill(ds);
return ds.Tables[0];
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
return done;
}
}
Thank you all
The main thing I can see is you are assigning two different things to your "s" variable.
At this point db.Run(s) the value is "Insert into Department etc" and you have lost the first sql string you assigned to "s"
Try:
string s = "Insert into Course(Course_ID,Name_of_course) values ('" + tbid.Text + "','" + tbcourse_name.Text + "')";
s += "INSERT INTO Department (DepName,College,DeptID) VALUES ('"+dddept.SelectedValue+"','"+ddcollege.SelectedValue+"','"+tbdeptID.Text+"')";
Notice the concatenation(+=). Otherwise as mentioned above using a stored procedure or entity framework would be a better approach. Also try to give your variables meaningful names. Instead of "s" use "insertIntoCourse" or something that describes what you are doing
When a value is inserted into a table(Table1) and and value has to be entered to into another table(Table2) on insertion of value to Table1, you can use triggers.
https://msdn.microsoft.com/en-IN/library/ms189799.aspx
"tbdeptID.Text" is giving you the department Id only right? You should be able to modify your first statement
string s = "Insert into Course(Course_ID,Name_of_course,) values ('" + tbid.Text + "','" + tbcourse_name.Text + "',)";
Please start running SQL Profiler, it is a good tool to see what is the actual query getting executed in server!

Select statement using OleDbCommand throws InvalidOperationException

I need to find a record in C# but I get an InvalidOperationException:
public static Auto findAuto(int kfznr)
{
Auto retAuto = new Auto();
try
{
myOleDbConnection.Open();
string query = "SELECT * FROM Auto WHERE Auto.KFZNR = " + kfznr;
OleDbCommand select = new OleDbCommand();
select.Connection = myOleDbConnection;
select.CommandText = query;
OleDbDataReader reader = select.ExecuteReader();
while (reader.Read())
{
Auto at = new Auto(Convert.ToInt32(reader[0]), Convert.ToString(reader[1]), Convert.ToString(reader[2]));
retAuto = at;
}
}
catch (OleDbException e)
{
Console.WriteLine(e.ToString());
}
return retAuto;
}
I get the error in the while loop at the creation of the new Auto.
When I run the same query in the SQLDeveloper I get one record (take a look at the first screenshot) but in my C# program I get there is no data for my row/cell.
When I hover the reader I get the following image. It says that the reader has rows:
Hope that you can help me fix this problem.
You need to use reader.GetValue(0)
public static Auto findAuto(int kfznr)
{
Auto retAuto = new Auto();
try
{
myOleDbConnection.Open();
string query = "SELECT * FROM Auto WHERE Auto.KFZNR = " + kfznr;
OleDbCommand select = new OleDbCommand();
select.Connection = myOleDbConnection;
select.CommandText = query;
OleDbDataReader reader = select.ExecuteReader();
while (reader.Read())
{
Auto at = new Auto(Convert.ToInt32(reader.GetValue(0)), Convert.ToString(reader.GetValue(1)), Convert.ToString(reader.GetValue(2)));
retAuto = at;
}
}
catch (OleDbException e)
{
Console.WriteLine(e.ToString());
}
return retAuto;
}
Also wanted to add...you can access the reader values by column name as well using:
reader["ColumnName"]...don't forget the "" around the name of the column ;)
public static Auto findAuto(int kfznr)
{
Auto retAuto = new Auto();
try
{
myOleDbConnection.Open();
string query = "SELECT * FROM Auto WHERE Auto.KFZNR = " + kfznr;
OleDbCommand select = new OleDbCommand();
select.Connection = myOleDbConnection;
select.CommandText = query;
OleDbDataReader reader = select.ExecuteReader();
while (reader.Read())
{
Auto at = new Auto(Convert.ToInt32(reader["col1"]), Convert.ToString(reader["col2"]), Convert.ToString(reader["col3"]));
retAuto = at;
}
}
catch (OleDbException e)
{
Console.WriteLine(e.ToString());
}
return retAuto;
}

Categories