I'm trying to update values of two tables such as from dataGridview
Order table and Orderdetail table as shown in my image.
It's working to update Order table but updating OrderdDetail table is not working. I want to update all rows with the same OrderNr. I get OrderDetail values from dataGridView. Here is my code:
private void UpdateOrder(int paymentTypes)
{
try
{
string connstring = ConfigurationManager.ConnectionStrings["Db"].ConnectionString;
using (OleDbConnection conn = new OleDbConnection(connstring))
{
conn.Open();
using (OleDbCommand cmd = new OleDbCommand("UPDATE [Orders] SET Amount = #Amount, Tax = #Tax , ToPay = #ToPay WHERE OrderNr = #OrderNumber", conn))
{
// This First table Orders updating fine
cmd.Parameters.AddWithValue("#Amount", txtAmount.Text);
cmd.Parameters.AddWithValue("#Tax", txtTax.Text);
cmd.Parameters.AddWithValue("#ToPay", txtToPay.Text);
cmd.ExecuteNonQuery();
}
// Here begin for OrderDetails table and not working to update.
foreach (DataGridViewRow row in dgvCart.Rows)
{
using (OleDbCommand cmd = new OleDbCommand("UPDATE [OrdersItems] SET OrderNr = #OrderNumber, ProductId = #ProductId, Quantity = #Quantity, WHERE OrderNr = #OrderNumber AND ProductId = #ProductId", conn))
{
cmd.Parameters.AddWithValue("#Quantity", Convert.ToInt32(row.Cells["Quantity"].Value));
cmd.Parameters.AddWithValue("#OrderNumber", txtOrderNumber.Text);
cmd.Parameters.AddWithValue("#ProductId", Convert.ToDecimal(row.Cells["ProductId "].Value));
cmd.ExecuteNonQuery();
}
}
MessageBox.Show("Updating successfully !", "Success", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
There are a couple of errors in your code.
First you have a syntax error in your query
using (OleDbCommand cmd = new OleDbCommand(#"UPDATE [OrdersItems]
SET OrderNr = #OrderNumber, ProductId = #ProductId, Quantity = #Quantity,
WHERE OrderNr = #OrderNumber AND ProductId = #ProductId", conn))
There is a comma before the WHERE statement that you should remove.
Second, the first query is missing the parameter for OrderNumber.
Third point.
In OleDb parameters are positional, even if you can name them you should put them in the same order in which they appear in the query and you need to put it again if you use them two times (OrderNumber & ProductID appear both in the SET part and in the WHERE)
cmd.Parameters.AddWithValue("#OrderNumber", txtOrderNumber.Text);
cmd.Parameters.AddWithValue("#ProductId", Convert.ToDecimal(row.Cells["ProductId "].Value));
cmd.Parameters.AddWithValue("#Quantity", Convert.ToInt32(row.Cells["Quantity"].Value));
cmd.Parameters.AddWithValue("#OrderNumber", txtOrderNumber.Text);
cmd.Parameters.AddWithValue("#ProductId", Convert.ToDecimal(row.Cells["ProductId "].Value));
However you don't need to update the ProductID and the OrderNumber. They cannot change otherwise this query could not find the rows that you want to update.
using (OleDbCommand cmd = new OleDbCommand(#"UPDATE [OrdersItems]
SET Quantity = #Quantity
WHERE OrderNr = #OrderNumber AND ProductId = #ProductId", conn))
with only three parameters in the correct order
cmd.Parameters.AddWithValue("#Quantity", Convert.ToInt32(row.Cells["Quantity"].Value));
cmd.Parameters.AddWithValue("#OrderNumber", txtOrderNumber.Text);
cmd.Parameters.AddWithValue("#ProductId", Convert.ToDecimal(row.Cells["ProductId "].Value));
Related
I am having problem with my code with the update query it shows the error syntax error in update statement. I would like to insert in data into an existing row with the columns already created.
private void save_care_Click(object sender, EventArgs e)
{
if (textBox2.Text=="")
{
//Checking if workorder exist in database
connection.Open();
OleDbCommand checkrecord = new OleDbCommand("SELECT COUNT(*) FROM [c# barcode] WHERE ([Workorder] = #workorder)", connection);
checkrecord.Parameters.AddWithValue("#workorder", textBox2.Text);
int recordexist = (int)checkrecord.ExecuteScalar();
if (recordexist > 0)
{
//add data if it exist
string cmdText = "UPDATE [c# barcode] SET ([Close from care],[Name care]) VALUES (#Close, #name) WHERE ([Workorder] = #workorder)";
using (OleDbCommand cmd = new OleDbCommand(cmdText, connection))
{
cmd.Parameters.AddWithValue("#workorder", textBox2.Text);
cmd.Parameters.AddWithValue("#Close", DateTime.Now.ToString("d/M/yyyy"));
cmd.Parameters.AddWithValue("#name", label4.Text);
cmd.ExecuteNonQuery();
textBox2.Clear();
connection.Close();
}
connection.Close();
}
else
{
//inserting workorder if it does not exist
string cmdText = "INSERT INTO [c# barcode] ([Workorder], [Close from care], [Name care]) VALUES (#workorder, #Close, #name)";
using (OleDbCommand cmd = new OleDbCommand(cmdText, connection))
{
cmd.Parameters.AddWithValue("#workorder", textBox2.Text);
cmd.Parameters.AddWithValue("#Close", DateTime.Now.ToString("d/M/yyyy"));
cmd.Parameters.AddWithValue("#name", label4.Text);
if (cmd.ExecuteNonQuery() > 0)
{
textBox2.Clear();
MessageBox.Show("Insert successful, workorder has not been handed over, please check");
}
else
{
textBox2.Clear();
MessageBox.Show("Please rescan");
connection.Close();
}
connection.Close();
}
}
}
else
MessageBox.Show("No data, Please scan workorder");
}
Error is at cmd.ExecuteNonQuery(); line.
For example the table in the picture under workorder there is a test4 the update will insert data into the column [Close from care] and [name care] in the test4 row
I believe that you are using the INSERT syntax for an UPDATE. You should use the UPDATE syntax.
The example from Microsoft is as follows:
UPDATE Orders
SET OrderAmount = OrderAmount * 1.1,
Freight = Freight * 1.03
WHERE ShipCountry = 'UK';
So if we update yours to match, it should look like this:
UPDATE [c# barcode]
SET [Close from care] = #Close,
[Name care] = #name
WHERE [Workorder] = #workorder
Obviously the newlines aren't important, it's just to make it easier to read.
Hi i have Attendance and Departure System on mvc Using Ado.Net My Connection Name is (DBConnection) i have Two Method One For OnClick TimeIn and AND OTHER one for TimeOut , My DataBase Name LoginTime and My Table is Attendance I have Problem in onclick timein Btton check if row not exist in my Attendance table insert new row else show Message "You Already TimeIn"
public void Addtime(Attendance AddTim)
{
SqlCommand comm = new SqlCommand("select * from Attendance where UserID=#user", conn);
comm.Parameters.AddWithValue("#user", AddTim.UserID);
conn.Open();
var rd = comm.ExecuteReader();
bool sat = rd.Read();
conn.Close();
if (sat == true)
{
SqlCommand updCommand = new SqlCommand("UPDATE Attendance SET TimeIn=#timein WHERE UserID=#userid", conn);
updCommand.Parameters.AddWithValue("#userid", AddTim.UserID);
updCommand.Parameters.AddWithValue("#timein", DateTime.Now);
conn.Open();
int rowsUpdated = updCommand.ExecuteNonQuery();
var rdr = comm.ExecuteReader();
conn.Close();
}
else
{
SqlCommand insCommand = new SqlCommand("INSERT into Attendance (UserID,TimeIn) VALUES (#userid,#timein)", conn);
insCommand.Parameters.AddWithValue("#userid", AddTim.UserID);
insCommand.Parameters.AddWithValue("#timein", DateTime.Now);
conn.Open();
int rowsUpdated = insCommand.ExecuteNonQuery();
var rdr = comm.ExecuteReader();
conn.Close();
}
}
public void Addtimout(Attendance addtimout)
{
SqlCommand UpDCommand = new SqlCommand("UPDATE Attendance SET TimeOut=#timeout WHERE UserID=#userid", conn);
UpDCommand.Parameters.AddWithValue("#UserID", addtimout.UserID);
UpDCommand.Parameters.AddWithValue("#timeout", DateTime.Now);
conn.Open();
UpDCommand.ExecuteNonQuery();
conn.Close();
}
}
}
There is probably more going on then what I can deduce from your question and no real explanation of the error (if any) you are getting. If this is so please post the error or unexpected behavior, and the database schema would also be helpful
I did notice that you are doing multiple insert or update statements in that block, as you are executing each query twice; once as a NonQuery and again as a Reader.
int rowsUpdated = insCommand.ExecuteNonQuery();
var rdr = comm.ExecuteReader();
The original query to check doesn't look to great to me. If you simply want to check for a row count, you could use SELECT Count(*), and execute via ExecuteScalar(). This will remove the overhead of a Reader
public void Addtime(Attendance AddTim) {
SqlCommand comm = new SqlCommand("select Count(*) from Attendance where UserID=#user", conn);
comm.Parameters.AddWithValue("#user", AddTim.UserID);
conn.Open();
int uc = (int)comm.ExecuteScalar();
bool sat = (uc > 0);
conn.Close();
I have two SQL tables (SalesCategory and ProductLine), each with two columns. A product category cannot be associated with a Sales Category and a Product Line at the same time. Users can, however, change, for example, Product Category ABC to be associated with Sales Category 123 instead of Product Line 456. When something like this happens, I want to remove the record of Product Category ABC from the ProductLine SQL table and UPDATE the SalesCategory with the ID of Product Category ABC. But I am not sure how to do this without making another separate DELETE function and calling them inside the save function for the SQL table in question. I feel like I'm putting in too many functions related to these 2 SQL tables....
As an important side note, Product Categories cannot be associated with more than one Product Line or more than one Sales Category.
Is there a better way to setup the code so I don't have a bunch of functions floating around associated with two SQL database tables? Or is this the best way to go about things?
Here is my code as it is now:
//Get current Product Line and Sales Cateogry data for the current Category.
//These two functions are called in the Page_Load
protected string getProductLine()
{
string retVal = "";
try
{
using (SqlConnection cn = new SqlConnection(ConfigurationManager.ConnectionStrings["AbleCommerce"].ToString()))
{
cn.Open();
SqlCommand cmd = new SqlCommand("SELECT ProductLine FROM ProductLine WHERE uidCategory = #CategoryID", cn);
cmd.Parameters.Add(new SqlParameter("#CategoryID", _CategoryId));
cmd.CommandType = CommandType.Text;
using (IDataReader reader = cmd.ExecuteReader())
{
while (reader.Read())
{
if (reader["ProductLine"].ToString() != "")
{
productLineTxt.Text = reader["ProductLine"].ToString();
retVal = productLineTxt.Text;
}
else
{
retVal = "";
}
}
}
cn.Close();
}
}
catch (Exception ex)
{
//
}
return retVal;
}
protected string getSalesCategory()
{
string retVal = "";
try
{
using (SqlConnection cn = new SqlConnection(ConfigurationManager.ConnectionStrings["AbleCommerce"].ToString()))
{
cn.Open();
SqlCommand cmd = new SqlCommand("SELECT SalesCat FROM SalesCategory WHERE uidCat = #CategoryID", cn);
cmd.Parameters.Add(new SqlParameter("#CategoryID", _CategoryId));
cmd.CommandType = CommandType.Text;
using (IDataReader reader = cmd.ExecuteReader())
{
while (reader.Read())
{
if (reader["SalesCat"].ToString() != "")
{
salesCatTxt.Text = reader["SalesCat"].ToString();
retVal = salesCatTxt.Text;
}
else
{
retVal = "";
}
}
}
cn.Close();
}
}
catch (Exception x)
{
//
}
return retVal;
}
//These two functions are called in the saveSalesCategory() and saveProductLine() functions respectively. They determine if those save functions should perform an UPDATE or INSERT. This is meant to prevent a Product Category from having association with more than one Product Line or Sales Category
protected bool salesCatExists()
{
bool retVal = true;
try
{
using (SqlConnection cn = new SqlConnection(ConfigurationManager.ConnectionStrings["AbleCommerce"].ToString()))
{
cn.Open();
SqlCommand cmd = new SqlCommand();
cmd.Connection = cn;
cmd.CommandText = "SELECT COUNT(*) AS 'Exists' FROM SalesCategory WHERE uidCat = #CategoryID";
cmd.Parameters.Add(new SqlParameter("#CategoryID", _CategoryId));
cmd.Parameters.Add(new SqlParameter("#SalesCategory", salesCatTxt.Text));
cmd.CommandType = CommandType.Text;
using (IDataReader reader = cmd.ExecuteReader())
{
while (reader.Read())
{
if (Convert.ToInt32(reader["Exists"]) == 0)
{
retVal = false;
}
else
{
retVal = true;
}
}
}
cn.Close();
}
}
catch (Exception x)
{
//
}
return retVal;
}
protected bool productLineExists()
{
bool retVal = true;
try
{
using (SqlConnection cn = new SqlConnection(ConfigurationManager.ConnectionStrings["AbleCommerce"].ToString()))
{
cn.Open();
SqlCommand cmd = new SqlCommand();
cmd.Connection = cn;
cmd.CommandText = "SELECT COUNT(*) AS 'Exists' FROM ProductLine WHERE uidCategory = #CategoryID";
cmd.Parameters.Add(new SqlParameter("#CategoryID", _CategoryId));
cmd.Parameters.Add(new SqlParameter("#ProductLine", productLineTxt.Text));
cmd.CommandType = CommandType.Text;
using (IDataReader reader = cmd.ExecuteReader())
{
while (reader.Read())
{
if (Convert.ToInt32(reader["Exists"]) == 0)
{
retVal = false;
}
else
{
retVal = true;
}
}
}
cn.Close();
}
}
catch (Exception x)
{
//
}
return retVal;
}
//Save new or update old Product Line and Sales Category data for the current Category
protected void saveProductLine()
{
try
{
string update1 = "UPDATE ProductLine SET ProductLine = #ProductLine WHERE uidCategory = #CategoryID";
string update2 = "UPDATE ProductLine SET ProductLine = '' AND uidCategory = '' WHERE uidCategory = #CategoryID";
string insert = "INSERT INTO ProductLine (uidCategory, ProductLine) VALUES(#CategoryID, #ProductLine)";
using (SqlConnection cn = new SqlConnection(ConfigurationManager.ConnectionStrings["AbleCommerce"].ToString()))
{
cn.Open();
SqlCommand cmd = new SqlCommand();
cmd.Connection = cn;
cmd.Parameters.Add(new SqlParameter("#CategoryID", _CategoryId));
cmd.Parameters.Add(new SqlParameter("#ProductLine", productLineTxt.Text));
cmd.CommandType = CommandType.Text;
if (getProductLine() == "")
{
cmd.CommandText = insert;
}
else
{
productLineTxt.Text = getProductLine();
cmd.CommandText = update;
}
cmd.ExecuteNonQuery();
cn.Close();
}
}
catch (Exception ex)
{
//
}
}
protected void saveSalesCategory()
{
string update = "UPDATE SalesCategory SET SalesCat = #SalesCategory WHERE uidCat = #CategoryID";
string insert = "INSERT INTO SalesCategory (uidCat, SalesCat) VALUES(#CategoryID, #SalesCategory)";
try
{
using (SqlConnection cn = new SqlConnection(ConfigurationManager.ConnectionStrings["AbleCommerce"].ToString()))
{
cn.Open();
SqlCommand cmd = new SqlCommand();
cmd.Parameters.Add(new SqlParameter("#CategoryID", _CategoryId));
cmd.Parameters.Add(new SqlParameter("#SalesCategory", salesCatTxt.Text));
cmd.Connection = cn;
cmd.CommandType = CommandType.Text;
if (salesCatExists() == false)
{
cmd.CommandText = insert;
}
else
{
cmd.CommandText = update;
}
cmd.ExecuteNonQuery();
cn.Close();
}
}
catch (Exception x)
{
//
}
}
You might look into the SQL MERGE statement. I'm not sure I completely understand what you're hoping to do enough to give a code example of how it might help you, but that sounds like it might do something like your goal.
It'll let you, for instance, check one table (whether an actual table or just a table-valued-variable) against another given a key or set of keys, then take action when records match or when they don't match.
I suppose I can give a quick example, though:
This query could handle much of the logic in your saveSalesCategory method:
MERGE SalesCategory AS T
USING (VALUES ((#CategoryID, #SalesCategory)) AS S (uidCat, SalesCat)
ON (T.uidCat = S.uidCat)
WHEN MATCHED THEN
UPDATE SET SalesCat = S.SalesCat
WHEN NOT MATCHED THEN
INSERT (uidCat, SalesCat) VALUES (S.uidCat, S.SalesCat)
As you'll notice, it checks to see whether any records exist, then inserts or updates accordingly. This gets rid of your need to run salesCatExists() and use multiple TSQL queries.
I recognize that this doesn't answer your question (I think?) but I hope it at least guides you a bit in the right direction, since I'm still not overly sure what exactly you are looking for.
You can't have an update to one table and a delete to another table like this in a single command. It seems that the data structure is what you are fighting the most here. If your ProductCategory table had a column for ReferenceType this would be pretty simple. You would be able to update the ReferenceType and the foreign key value in a single pass. With they way you have put this together you also are going to have challenges with referential integrity because the value in ProductCategory would be a foreign to one or the other table depending on which type it is.
Your code sample looks like it isn't trying to do everything that you descriptions states. Maybe you just hadn't gotten to the delete part. I think a couple of stored procedures might be helpful. I condensed a couple of your methods into one stored proc, and you can do the same thing for the Product Line. I just wasn't sure where to put the DELETE statement. Is this the right direction? If so, we can figure out where to put that delete ;)
CREATE PROCEDURE SaveSalesCategory
#CategoryID INT ,
#SalesCategory INT
AS
BEGIN
DECLARE #SalesCatCount INT = ( SELECT COUNT(*) AS 'Exists'
FROM SalesCategory
WHERE uidCat = #CategoryID
)
IF #SalesCatCount = 0
BEGIN
INSERT INTO SalesCategory
( uidCat, SalesCat )
VALUES ( #CategoryID, #SalesCategory )
END
ELSE
BEGIN
UPDATE SalesCategory
SET SalesCat = #SalesCategory
WHERE uidCat = #CategoryID
END
END
GO
Use an OUTPUT clause (MSDN)
DELETE ProductLine
WHERE uidCategory = #CategoryID
OUTPUT column1,column2,etc INTO SalesCategory
or
DELETE SalesCategory
WHERE uidCategory = #CategoryID
OUTPUT column1,column2,etc INTO ProductLine
You could put a trigger on both of those tables so that when you insert a new record or update an existing record the DB looks to your other table for that category and deletes that record.
Not all of your parameters were used in your example code and it's kind of long so I don't think this code, as written, will do exactly what you need but the concept I think should work.
CREATE TRIGGER dbo.TRG_SalesCategory_RECORD
ON SalesCategory
AFTER INSERT, UPDATE
AS
BEGIN
SET NOCOUNT ON;
Delete from ProductLine
Where CategoryID = (select CategoryID from INSERTED)
END
GO
CREATE TRIGGER dbo.TRG_ProductLine_RECORD
ON ProductLine
AFTER INSERT, UPDATE
AS
BEGIN
SET NOCOUNT ON;
Delete from SalesCategory
Where CategoryID = (select CategoryID from INSERTED)
END
GO
My goal is to update the QTY for each SKU. I am using a SqlDataAdapter to accomplish this. The program runs fine. Just that no result happens.
QUESTION: Why is no result happening? My database remains unchanged.
Code below
public static void updateInventoryfromAMZ(DataTable datatable)
{
int index = 0;
string connString = System.Configuration.ConfigurationManager.ConnectionStrings["MyConnectionString"].ToString();
DataSet amzInventoryDataSet = new DataSet("AMZINVDATASET");
amzInventoryDataSet.Tables.Add(datatable);
// FOR EACH ROW - PERFORM AN UPDATE //
using (SqlConnection connection = new SqlConnection(connString))
{
SqlDataAdapter adapter = new SqlDataAdapter();
foreach (DataRow row in amzInventoryDataSet.Tables[index].Rows)
{
string sku = datatable.Rows[index]["seller-sku"].ToString();
string qty = datatable.Rows[index]["quantity"].ToString();
// Create the UpdateCommand.
SqlCommand command = new SqlCommand(
"UPDATE Inventory SET qty = #qty" +
"WHERE sku = #sku", connection);
// Add the parameters for the UpdateCommand.
command.Parameters.Add("#qty", SqlDbType.Int, qty.Length, qty);
command.Parameters.Add("#sku", SqlDbType.VarChar, sku.Length, sku);
adapter.UpdateCommand = command;
adapter.Update(amzInventoryDataSet.Tables[index]);
index++;
}
}
}
When you concatenating two sql strings, you better add space at the end of first string or at the beginning of second string. As Gordon Linoff pointed out your sql statement is incorrect. And also setting parameters and the values need to be change depending on the type of the parameters.
try below code, I have use SqlCommand and ExecuteNonQuery method to update each row data
using (SqlConnection connection = new SqlConnection(connString))
using (SqlCommand cmd = new SqlCommand("UPDATE Inventory SET qty = #qty WHERE sku = #sku", connection))
{
connection.Open();
var paramqty= cmd.Parameters.Add("#qty", SqlDbType.Int);
var parasku = cmd.Parameters.Add("#sku", SqlDbType.VarChar);
foreach (DataRow row in amzInventoryDataSet.Tables[0].Rows)
{
parasku.Value = row["seller-sku"].ToString();
paramqty.Value = int.Parse(row["quantity"].ToString());
cmd.ExecuteNonQuery();
}
}
I am thinking your problem are these lines:
"UPDATE Inventory SET qty = #qty" +
"WHERE sku = #sku", connection);
They are going to produce a string like:
"UPDATE Inventory SET qty = #qtyWHERE sku = #sku", connection);
And the variable #qtyWHERE is not defined.
Try this instead:
"UPDATE Inventory SET qty = #qty WHERE sku = #sku", connection);
I have 2 tables like Item and Image, first table tbl_Item has 2 fields those are item code,item name and second table tbl_Image has 2 fields like item code and item image. I have fields like item code, item name, item image and one button. When i click the submit button those records are inserted into both two tables. I want to insert the data into two tables How it is possible? Can any body suggest me?
cmd.Connection = new SqlConnection(ConfigurationManager.ConnectionStrings[1].ToString());
cmd.CommandText = "insert into tbl_item (#itemcode,#itemname) values(ItemCode,ItemName)";
cmd.CommandText = "insert into tbl_image (#itemcode,#itemimage) values(ItemCode,ItemImage)";
Yes, you can insert into two tables simultaneously. Check this code:
Note: Your original insert query was wrong, I have modified it.
public void InsertIntoDataBase(int itemCode, string itemName, string itemImage)
{
string connString = ConfigurationManager.ConnectionStrings[1].ToString();
string query1 = #"insert into tbl_item (ItemCode,ItemName) values(#itemcode,#itemname)";
string query2 = #"insert into tbl_image (ItemCode,ItemImage) values(#itemcode,#itemimage)";
SqlConnection conn = new SqlConnection(connString);
try
{
// Exc]ecute the first query.
SqlCommand cmd = new SqlCommand(query1, conn);
cmd.Parameters.Add("#itemcode", SqlDbType.Int, 10, "ItemCode").Value = itemCode; // Pass the actual Item code
cmd.Parameters.Add("#itemname", SqlDbType.Text, 20, "ItemName").Value = itemName; //Pass the actual Item name
cmd.ExecuteNonQuery();
// Exc]ecute the second query.
cmd = new SqlCommand(query2, conn);
cmd.Parameters.Add("#itemcode", SqlDbType.Int, 10, "ItemCode").Value = itemCode; // Pass the actual Item code
cmd.Parameters.Add("#itemimage", SqlDbType.Text, 20, "ItemImage").Value = itemImage; // Pass the actual Item image
cmd.ExecuteNonQuery();
}
catch (Exception e)
{
}
finally
{
conn.Close();
}
}
if you want to insert both record in single command execution then join query with ";".
such as
cmd.CommandText = "insert into tbl_item (#itemcode,#itemname) values(ItemCode,ItemName);insert into tbl_image (#itemcode,#itemimage) values(ItemCode,ItemImage)";