Insert the date into 2 tables - c#

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)";

Related

Updating multiple rows with the same Ordernumber

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));

INSERT INTO Table (Column) VALUE (email)

I want to insert email in Table with only one column. I tried on 2 way. First time I tried with commandText and second time I tried with parapeters. But the both solution give me the same error.
System.Data.OleDb.OleDbException: 'Syntax error in INSERT INTO statement.'
I don't see any error in INSERT STATEMENT. Maybe the problem is in TABLE?
using (OleDbCommand cmd = new OleDbCommand())
{
cmd.Connection = conn;
cmd.CommandText = "SELECT COUNT (email) FROM [User] WHERE [email] LIKE '" + userEmail + "';";
conn.Open();
int count = Convert.ToInt32(cmd.ExecuteScalar()); // This passed
if (count == 0)
{
string query = #"INSERT INTO User (email) VALUES (#email)";
string cmdText= #"INSERT INTO User (email) VALUES ('"+userEmail+"')";
OleDbCommand command = new OleDbCommand(cmdText, conn);
// command.Parameters.AddWithValue("#email", "userEmail");
// command.CommandText = query;
command.ExecuteNonQuery(); // I GOT ERROR HERE
}
conn.Close();
}
User is a keyword. You should INSERT INTO [USER] instead
string cmdText= #"INSERT INTO User (email)) VALUES ('"+userEmail+"')";
you have one ')' too many after (email)

Having some trouble using scope identity

I have two tables, one containing names, and one containing rates and other data that is lined to each name. After I insert a new name into table A, I want to get the newly auto generated PK to now use to insert into my other table B with rates.
How can I do this? I read about scope_identity online but I'm not sure how to use it.
This is what I have so far:
SqlConnection con = new SqlConnection(pubvar.x);
SqlCommand command = con.CreateCommand();
command.CommandText ="Insert into A values('" +Name + "')";
SqlCommand command2 = con.CreateCommand();
command2.CommandText = "Insert into B values(....)";
SELECT SCOPE_IDENTITY();
con.Open();
command.ExecuteNonQuery();
con.Close();
Considering the case you've described, I don't see any need to return the identity from the database. You can simply issue both statements in one command:
using (var cnx = new SqlConnection(pubvar.x))
using (var cmd = new SqlCommand
{
Connection = cnx,
CommandText = #"
insert into A (Name) values (#name)
insert into B (A_ID, Rate) values (scope_identity(), #rate)
",
Parameters =
{
new SqlParameter("#name", name),
new SqlParameter("#rate", .5m) //sample rate
}
})
{
cnx.Open();
cmd.ExecuteNonQuery();
}

Update Database from Dataset

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);

How to retrive last enty in ACCESS database using C# via OleDB with sql commands

Again me with me form base program (with visual C# 2010)
After getting most of my program to work I started adding some small "extras"
Here is the problem: when I add a new item, I want to open a MessageBox and write the id of the new item.
Table = Item, field = item_id
Tried using:
cmd.CommandText = "SELECT LAST(item_id) FROM Item";
OleDbDataReader dr = cmd.ExecuteReader();
while (dr.Read())
{
id = dr["item_id"].ToString();
}
Here is the full function:
public void ItemInsert(string name,string creator,string publishing,string itemType,string genere, string year)
{
string id ="";
cmd.CommandText = "INSERT INTO Item (item_name, creator_name,publishing_name,item_type,genre,year_publication,location) VALUES (#item_name, #creator_name,#publishing_name,#item_type,#genre,#year_publication,#location);";
cmd.Parameters.AddWithValue("#item_name", name);
cmd.Parameters.AddWithValue("#creator_name", creator);
cmd.Parameters.AddWithValue("#publishing_name",publishing);
cmd.Parameters.AddWithValue("#item_type", itemType);
cmd.Parameters.AddWithValue("#genre",genere);
cmd.Parameters.AddWithValue("#year_publication",year);
cmd.Parameters.AddWithValue("#location", 0);//location=0 when in library
con.Open(); // open the connection
cmd.ExecuteNonQuery();
//get item id
cmd.CommandText = "SELECT LAST(item_id) FROM Item";
OleDbDataReader dr = cmd.ExecuteReader();
while (dr.Read())
{
id = dr["item_id"].ToString();
}
con.Close();
MessageBox.Show("Item ID : " + id+"","Added new item");
}
Replace:
cmd.CommandText = "SELECT LAST(item_id) FROM Item";
With:
cmd.CommandText = "SELECT ##IDENTITY";
In my case the "IDENTITY" stuff has not worked (maybe because the field was not PK or AI). It was always the id "0"
i used this query:
cmd.CommandText = "SELECT TOP 1 item_id FROM Item ORDER BY item_id DESC";
Note that the "TOP 1" is equal to other sql-dialect's "LIMIT 1"
so in short, without setting further cmd options:
object scalarInt = new OleDbCommand("SELECT TOP 1 item_id FROM Item ORDER BY item_id DESC", con).ExecuteScalar();
int lastItemId = (int?) scalarInt ?? 0;
where the 0 at the end of the last line is the default return value, if there are no entries yet. you may use 1 as database Id's typically start with 1.

Categories

Resources