我有一个datagridview,它由各种操作和用户对数据的操作创建。 我想立即将gridview的所有数据插入到数据库中,我知道我可以尝试类似这样的代码:
for(int i=0; i< dataGridView1.Rows.Count;i++)
{
string StrQuery= @"INSERT INTO tableName VALUES (" + dataGridView1.Rows[i].Cells["ColumnName"].Value +", " + dataGridView1.Rows[i].Cells["ColumnName"].Value +");";
try
{
using (SqlConnection conn = new SqlConnection(ConnString))
{
using (SqlCommand comm = new SqlCommand(StrQuery, conn))
{
conn.Open();
comm.ExecuteNonQuery();
}
}
}
但每次插入记录时创建新连接是否公平? datagrid可能包含很多行......有没有办法一次性将所有数据都传递到服务器并在sql中循环以插入所有数据?
答案 0 :(得分:16)
如果移动for循环,则不必进行多个连接。只需快速编辑代码块(完全不正确):
string StrQuery;
try
{
using (SqlConnection conn = new SqlConnection(ConnString))
{
using (SqlCommand comm = new SqlCommand())
{
comm.Connection = conn;
conn.Open();
for(int i=0; i< dataGridView1.Rows.Count;i++)
{
StrQuery= @"INSERT INTO tableName VALUES ("
+ dataGridView1.Rows[i].Cells["ColumnName"].Text+", "
+ dataGridView1.Rows[i].Cells["ColumnName"].Text+");";
comm.CommandText = StrQuery;
comm.ExecuteNonQuery();
}
}
}
}
关于一次执行多个SQL命令,请查看以下链接: Multiple statements in single SqlCommand
答案 1 :(得分:1)
我认为最好的方法是使用TableAdapters而不是使用Commands对象,它的Update方法会将数据集或DataTable中所做的所有更改(更新,插入和删除)直接发送到数据库。通常在使用DataGridView时,您可以绑定到BindingSource,它允许您与数据源(如数据表或数据集)进行交互。
如果你这样工作,那么在你有界的DataGridView上你就可以做到:
this.customersBindingSource.EndEdit();
this.myTableAdapter.Update(this.myDataSet.Customers);
&#39; customersBindingSource&#39;是DataGridView的DataSource。
适配器的Update方法将更新单个数据表和 根据执行正确的命令(INSERT,UPDATE或DELETE) 表中每个数据行的RowState。
来自:https://msdn.microsoft.com/en-us/library/ms171933.aspx
因此,在使用Update方法时,DatagridView中所做的任何更改都将反映在数据库中。
有关TableAdapters的更多信息:https://msdn.microsoft.com/en-us/library/bz9tthwx.aspx
答案 2 :(得分:1)
请查看以下内容是否可以帮助您
Class Post_Sales
Public Shared Sub Post_sales()
Dim ITM_ID As Integer
Dim SLS_QTY As Integer
Dim SLS_PRC As Double
Dim SLS_AMT As Double
Dim DSPL_RCT As String
Dim TAX_CODE As Integer
'Format the current date and send it to a textbox
Form1.TextBox6.Text = System.DateTime.Now.ToString((" yyyy-MM-dd"))
'Open Connection
Dim con As New SqlConnection("Initial Catalog=Your Database here;Data source=.;Network Library=DBMSSOCN;User ID=sa;Password=")
con.Open()
'Insert Records into the database
For Each rw As DataGridViewRow In Form1.DataGridView1.Rows
ITM_ID = rw.Cells("Column1").Value
DSPL_RCT = rw.Cells("Column2").Value
SLS_QTY = rw.Cells("Column3").Value
SLS_PRC = rw.Cells("Column4").Value
SLS_AMT = rw.Cells("Column5").Value
TAX_CODE = rw.Cells("Column6").Value
Dim cmd As New SqlCommand("INSERT INTO DAY_PLUSALES (DT,ITM_ID,DSPL_RCT,SLS_QTY,SLS_PRC,SLS_AMT,TAX_CODE) values ('" & Form1.TextBox6.Text & "','" & ITM_ID & "','" & DSPL_RCT & "','" & SLS_QTY & "','" & SLS_PRC & "','" & SLS_AMT & "','" & TAX_CODE & "')", con)
cmd.ExecuteNonQuery()
Next
con.Close()
MessageBox.Show("Records Added to the SQL Database successfully!", "Records Updated ")
End Sub
结束班
答案 3 :(得分:0)
只需打开一次连接就可以做同样的事情。这样的事情。
for(int i=0; i< dataGridView1.Rows.Count;i++)
{
string StrQuery= @"INSERT INTO tableName VALUES (" + dataGridView1.Rows[i].Cells["ColumnName"].Value +", " + dataGridView1.Rows[i].Cells["ColumnName"].Value +");";
try
{
SqlConnection conn = new SqlConnection();
conn.Open();
using (SqlCommand comm = new SqlCommand(StrQuery, conn))
{
comm.ExecuteNonQuery();
}
conn.Close();
}
此外,根据您的具体情况,您可能希望将网格绑定到数据库。这将大大减少手工工作量: http://www.switchonthecode.com/tutorials/csharp-tutorial-binding-a-datagridview-to-a-database
答案 4 :(得分:0)
您遇到语法错误请尝试以下语法:
string StrQuery="INSERT INTO tableName VALUES ('" + dataGridView1.Rows[i].Cells[0].Value + "',' " + dataGridView1.Rows[i].Cells[1].Value + "', '" + dataGridView1.Rows[i].Cells[2].Value + "', '" + dataGridView1.Rows[i].Cells[3].Value + "',' " + dataGridView1.Rows[i].Cells[4].Value + "')";
答案 5 :(得分:0)
尝试使用此100%工作代码
string SQL = "", tableName = "tableName";
for (int i = 0; i < dataGridView1.Rows.Count; i++)
{
SQL = @"INSERT INTO " + tableName + " VALUES (";
for (int col = 0; col < dataGridView1.ColumnCount; col++)
{
string data = "";
if (dataGridView1.Rows[i].Cells[col].Value != null)
{
data = dataGridView1.Rows[i].Cells[col].Value.ToString();
}
SQL += "'" + data.Trim() + "'";
if (col < dataGridView1.ColumnCount - 1)
{
SQL += ",";
}
}
SQL += ")";
string finalSQL = SQL;
//INSERT to DB the finalSQL
}
您的数据现在已准备就绪,通过连接将finalSQL插入数据库中
答案 6 :(得分:-2)
for (int i = 0; i < dataGridView2.Rows.Count; i++)
{
SqlConnection con = new SqlConnection("Data Source=.;Initial Catalog=ID_Proof;Integrated Security=True");
SqlCommand cmd = new SqlCommand("INSERT INTO Restaurant (Customer_Name,Quantity,Price,Category,Subcategory,Item,Room_No,Tax,Service_Charge,Service_Tax,Order_Time) values (@customer,@quantity,@price,@category,@subcategory,@item,@roomno,@tax,@servicecharge,@sertax,@ordertime)", con);
cmd.Parameters.AddWithValue("@customer",dataGridView2.Rows[i].Cells[0].Value);
cmd.Parameters.AddWithValue("@quantity",dataGridView2.Rows[i].Cells[1].Value);
cmd.Parameters.AddWithValue("@price",dataGridView2.Rows[i].Cells[2].Value);
cmd.Parameters.AddWithValue("@category",dataGridView2.Rows[i].Cells[3].Value);
cmd.Parameters.AddWithValue("@subcategory",dataGridView2.Rows[i].Cells[4].Value);
cmd.Parameters.AddWithValue("@item",dataGridView2.Rows[i].Cells[5].Value);
cmd.Parameters.AddWithValue("@roomno",dataGridView2.Rows[i].Cells[6].Value);
cmd.Parameters.AddWithValue("@tax",dataGridView2.Rows[i].Cells[7].Value);
cmd.Parameters.AddWithValue("@servicecharge",dataGridView2.Rows[i].Cells[8].Value);
cmd.Parameters.AddWithValue("@sertax",dataGridView2.Rows[i].Cells[9].Value);
cmd.Parameters.AddWithValue("@ordertime",dataGridView2.Rows[i].Cells[10].Value);
con.Open();
cmd.ExecuteNonQuery();
con.Close();
MessageBox.Show("Added successfully!");