INSERT from DataGridView in DB - c#

my code only passes the first row to the database.
I am new to .NET. Who can suggest the problem.
for(int i = 0; i < dgvCSV_Datei.Rows.Count; i++)
{
var strQuery = "INSERT INTO Mobile (Name, IMEI, Hersteller) VALUES (#Name, #IMEI, #Hersteller)";
sqlCommand.CommandText = strQuery;
sqlCommand.Parameters.AddWithValue("#Name", dgvCSV_Datei.Rows[i].Cells[0].Value);
sqlCommand.Parameters.AddWithValue("#IMEI", dgvCSV_Datei.Rows[i].Cells[1].Value);
sqlCommand.Parameters.AddWithValue("#Hersteller", dgvCSV_Datei.Rows[i].Cells[2].Value);
sqlCommand.ExecuteNonQuery();
}
sqlCommand.ExecuteNonQuery();
sqlConnection.Close();

Your issue seems to be that you keep adding more parameters with the same name, without removing or changing the previous ones. Your code should instead look like this
const string strQuery = #"
INSERT INTO Mobile (Name, IMEI, Hersteller)
VALUES (#Name, #IMEI, #Hersteller);
";
using (var sqlConnection = new SqlConnection(YourConnString))
using (var sqlCommand = new SqlCommand(strQuery, sqlConnection))
{
sqlCommand.Parameters.Add("#Name", SqlDbType.VarChar, 100);
sqlCommand.Parameters.Add("#IMEI", SqlDbType.Varchar, 16);
sqlCommand.Parameters.Add("#Hersteller", SqlDbType.VarChar, 100);
sqlConnection.Open();
for(int i = 0; i < dgvCSV_Datei.Rows.Count; i++)
{
sqlCommand.Parameters["#Name"].Value = dgvCSV_Datei.Rows[i].Cells[0].Value;
sqlCommand.Parameters["#IMEI"].Value = dgvCSV_Datei.Rows[i].Cells[1].Value;
sqlCommand.Parameters["#Hersteller"].Value = dgvCSV_Datei.Rows[i].Cells[2].Value;
sqlCommand.ExecuteNonQuery();
}
}
A much better option is to use SqlBulkCopy. This is a highly performant bulk-copy mechanism specifically for plain inserts.
using (var bulk = new SqlBulkCopy(YourConnString, SqlBulkCopyOptions.CheckConstraints | SqlBulkCopyOptions.FireTriggers))
{
bulk.DestinationTableName = "Mobile";
bulk.ColumnMappings.Add(dgvCSV_Datei.Columns[0].ColumnName, "Name");
bulk.ColumnMappings.Add(dgvCSV_Datei.Columns[1].ColumnName, "IMEI");
bulk.ColumnMappings.Add(dgvCSV_Datei.Columns[2].ColumnName, "Hersteller");
bulk.WriteToServer(dgvCSV_Datei);
}

Related

The variable name '#Order_id' has already been declared. Variable names must be unique within a query batch or stored procedure

I am getting this error when I insert data from a gridview, I am inserting data into order details where I want to save same order ID with every order item but could not. I am developing in C# windows. I have search the web but that couldn't solve my problem. I am stuck at this point. Any help is appreciated.
I am adding my code lines that I am doing.
Kind regards
SqlCommand cmd1 = con.CreateCommand();
cmd1.CommandType = CommandType.Text;
cmd1.CommandText = "SELECT Top 1 * FROM Purchase_Order Order By P_Order_ID desc";
cmd1.ExecuteNonQuery();
DataTable dt = new DataTable();
SqlDataAdapter sda2 = new SqlDataAdapter(cmd1);
sda2.Fill(dt);
int OrderID = 0;
foreach (DataRow dr2 in dt.Rows)
{
OrderID = Convert.ToInt32(dr2["P_Order_ID"].ToString());
MessageBox.Show("order id +" +OrderID);
}
SqlCommand com2 = new SqlCommand();
com2.Connection = con;
for (int i = 0; i < dataGridView1.Rows.Count; i++)
{
foreach (DataRow dr2 in dt.Rows)
{
OrderID = Convert.ToInt32(dr2["P_Order_ID"].ToString());
}
string Query;
Query = #"INSERT INTO Purchase_Order_Detail (P_Order_ID, ProductID, PSC_ID, Pack_ID, Color, Base_ID, Quantity) VALUES (#OrderID, #ProductID, #Sub_ID, #PackID, #Colors, #BaseID, #Quantity);";
// com2.Parameters.Add("#OrderID" & dataGridView1.Rows(i).ToString(), dataGridView1(i));
com2.Parameters.AddWithValue("#OrderID", OrderID);
com2.Parameters.AddWithValue("#ProductID", dataGridView1.Rows[i].Cells[4].Value);
com2.Parameters.AddWithValue("#Sub_ID", dataGridView1.Rows[i].Cells[6].Value);
com2.Parameters.AddWithValue("#PackID", dataGridView1.Rows[i].Cells[8].Value);
com2.Parameters.AddWithValue("#Colors", dataGridView1.Rows[i].Cells[9].Value);
com2.Parameters.AddWithValue("#BaseID", dataGridView1.Rows[i].Cells[11].Value);
com2.Parameters.AddWithValue("#Quantity", dataGridView1.Rows[i].Cells[13].Value);
com2.CommandText = Query;
com2.ExecuteNonQuery();
//com2.Parameters.Clear();
}
You are trying to re-add a parameter which is already added to the SqlCommand. In your case you should add the parameters (and the query) before the for() loop and then fill these parameters with the new values for execution.
SqlCommand com2 = new SqlCommand();
com2.Connection = con;
com2.CommandText = #"INSERT INTO Purchase_Order_Detail (P_Order_ID,ProductID,PSC_ID,Pack_ID,Color,Base_ID,Quantity) VALUES (#OrderID,#ProductID,#Sub_ID, #PackID,#Colors,#BaseID,#Quantity);";
com2.Parameters.Add("#OrderID", ...type...);
com2.Parameters.Add("#ProductID", ...type...);
com2.Parameters.Add("#Sub_ID", ...type...);
com2.Parameters.Add("#PackID", ...type...);
com2.Parameters.Add("#Colors", ...type...);
com2.Parameters.Add("#BaseID", ...type...);
com2.Parameters.Add("#Quantity", ...type...);
for (int i = 0; i < dataGridView1.Rows.Count; i++)
{
foreach (DataRow dr2 in dt.Rows)
{
OrderID = Convert.ToInt32(dr2["P_Order_ID"].ToString());
}
com2.Parameters["#OrderId"].Value = OrderId;
com2.Parameters["#ProductID"].Value = dataGridView1.Rows[i].Cells[4].Value;
...
com2.ExecuteNonQuery();
}

Storing fields from a database in an array c#

I am trying to store all fields from a column in my microsoft access database in an array. I am using OleDb but I don't really know how to go about doing this.
I know that I have to have a loop to go over the table the amount of times as there are rows in the table, but I don't know how to store the current field in the current index of the array.
Any help would be greatly appreciated!
Here is a snippet of some of the code:
string[] tasks;
string sql = "SELECT [Task Name] FROM Tasks";
OleDbCommand cmd = new OleDbCommand(sql, conn);
OleDbDataReader dataReader = cmd.ExecuteReader();
if (dataReader.HasRows)
{
for (int i = 1; i <= 10; i++)
{
//tasks[i] = current field in table
}
}
Sounds like you want something like this?
string[] tasks;
string sql = "SELECT [Task Name] FROM Tasks";
using (OleDbCommand cmd = new OleDbCommand(sql, conn))
{
using (OleDbDataReader dataReader = cmd.ExecuteReader())
{
List<object[]> list = new List<object[]>();
if (dataReader.HasRows)
{
while (dataReader.Read())
{
object[] oarray = new object[dataReader.FieldCount];
list.Add(oarray);
for (int i = 1; i <= dataReader.FieldCount; i++)
{
oarray[i] = dataReader[i];
}
}
}
}
}

OleDbCommand Syntax error in INSERT INTO statement

I'm getting a syntax error in INSERT INTO statement and I can't figure out why. I've checked several different SO questions that were almost exactly the same as my problem and after changing my code this way and that way it still isn't working.
var cnnStr = String.Format("Provider=Microsoft.Jet.OLEDB.4.0;Data Source={0};", oldDb);
var cnn = new OleDbConnection(cnnStr);
cnn.Open();
//make new access table
using (OleDbCommand command = new OleDbCommand())
{
command.Connection = cnn;
command.CommandText = String.Format("CREATE TABLE [{0}] ([Tag] string, [Text] string)", newTable + "_Diff");
try
{
command.ExecuteNonQuery();
}
catch
{
//table already exists
}
}
//fill access table
using (OleDbCommand command = new OleDbCommand())
{
command.Connection = cnn;
command.CommandText = String.Format("INSERT INTO [{0}] (Tag, Text) VALUES (?, ?)", newTable + "_Diff");
command.Parameters.Add(new OleDbParameter("Tag", ""));
command.Parameters.Add(new OleDbParameter("Text", ""));
for (int i = 0; i < (diffText.Length - 1); i++)
{
command.Parameters["Tag"].Value = diffTag[i];
command.Parameters["Text"].Value = diffText[i];
command.ExecuteNonQuery();
}
}
cnn.Close();
Creating the table is working so I know there's not a problem with my connection, there's just something it doesn't like about my insert statement.
In your insert command put text inside a square bracket, "text" is a keyword
command.CommandText = String.Format("INSERT INTO [{0}] (Tag, [Text])
VALUES (?, ?)", newTable + "_Diff");
also make sure you are including your values with single quote
values ('?','?')
hope this works

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

Basic method to export cells values from GridView to SQL table

I need to read i little course about how to export a gridView in DevExpress to a SQL table..
like the values First Name, Father Name, Last Name to a table Employee and i have many rows..
how can I loop into every row and send data to the database..
Thx in advance
I tried this code:
string sql = #"INSERT INTO Emp (#FName, #MName,#LName, #Code, #TaxNb, #SSN, #EmploymentType, #DOB, #MarStat, #RegNum, #BadgeNum, #HireDate, #TaxSince, #HireSince, #ArEmpName, #ArFatherName, #ArLastName, ArPayUnit)";
DataTable table = new DataTable();
try
{
SqlConnection connection = new SqlConnection(#"workstation id = PC-PC; user id=sa;Password=sapassword; data source=pc-pc; persist security info=True;initial catalog=CleanPayrollTest2");
SqlCommand command = new SqlCommand(sql, connection);
SqlDataAdapter adapter = new SqlDataAdapter();
adapter.InsertCommand = command;
connection.Open();
// for (int i =0; i< gridView3.RowCount; i++)
//{
//command.Parameters.Add(#FirstName, gridView3.GetRowCellValue(i,gridView3.Columns));
//adapter.InsertCommand.ExecuteNonQuery();
//}
SqlParameter[] MyParams = new SqlParameter[28];
MyParams[0] = new SqlParameter("#FName", SqlDbType.VarChar, 20);
MyParams[0].SourceColumn = FirstName;
command.Parameters.Add("#FName", SqlDbType.VarChar, 20);
MyParams[1] = new SqlParameter("#MName", SqlDbType.VarChar, 20);
MyParams[1].SourceColumn = FatherName;
MyParams[2] = new SqlParameter("#LName", SqlDbType.VarChar, 20);
MyParams[2].SourceColumn = LastName;
From SqlDataAdapter Class:
The SqlDataAdapter, serves as a bridge between a DataSet and SQL
Server for retrieving and saving data.
In the scenario you described, there is no such need for a "bridge". You just use a SqlCommand, add the collection of SqlParameter to it, and then call ExecuteNonQuery() to perform the insert.
using(SqlConnection connection = new SqlConnection(#"workstation id = PC-PC; user id=sa;Password=sapassword; data source=pc-pc; persist security info=True;initial catalog=CleanPayrollTest2"))
{
using(SqlCommand command = new SqlCommand(sql, connection))
{
try
{
connection.Open();
for (int i =0; i< gridView3.RowCount; i++)
{
SqlParameter parameter = new SqlParameter();
// TODO: handle name accordingly (MName, LName etc.)
parameter.ParameterName = "#FName";
// TODO: handle type accordingly
parameter.SqlDbType = SqlDbType.NVarChar;
parameter.Direction = ParameterDirection.Input;
// TODO: use the field name accordingly
parameter.Value = Convert.ToString(gridView3.GetRowCellValue(i, "FieldName"));
// add the parameter to the command
command.Parameters.Add(parameter);
}
command.ExecuteNonQuery();
}
catch(Exception)
{
// TODO: handle the exception
}
}
}
Remark: you should dispose your SQL related objects in the code - a convenient way to do that is to use using statements.

Categories

Resources