![](/img/trans.png)
[英]Insert text file data into SQL Server database table of specific column
[英]Looping column data insert into SQL Server database
我是 C# 的新手。 我的问题是我想使用第 7 列及以上列的数量将 ean、描述、书籍代码、价格和折扣插入 SQL Server:
我当前的代码能够插入数据,但数量已经定义。 我正在考虑进行循环,但出现错误
必须声明标量变量
我不确定我的逻辑是否正确。
这是我的 SQL Server 表的屏幕截图:
我的代码:
private void button3_Click(object sender, EventArgs e)
{
using (SqlConnection conn = new SqlConnection(";Trusted_Connection=False"))
using (SqlCommand comm = new SqlCommand())
{
comm.Connection = conn;
conn.Open();
for (int i = 1; i < dataGridView2.Rows.Count; i++)
{
comm.CommandText = "INSERT INTO SOLine (CustID,Bookcode,Barcode,Description,Price,Disc,Qty) VALUES ('2058 KBC',@bookcode,@barcode,@desc,@price,@disc,@qty)";
SqlParameter bookcode = comm.Parameters.AddWithValue("@bookcode", dataGridView2.Rows[i].Cells["BOOKCODE"].Value);
SqlParameter barcode = comm.Parameters.AddWithValue("@barcode", dataGridView2.Rows[i].Cells["3"].Value);
SqlParameter desc = comm.Parameters.AddWithValue("@desc", dataGridView2.Rows[i].Cells["4"].Value);
SqlParameter price = comm.Parameters.AddWithValue("@price", dataGridView2.Rows[i].Cells["5"].Value);
SqlParameter disc = comm.Parameters.AddWithValue("@disc", dataGridView2.Rows[i].Cells["6"].Value);
//SqlParameter qty = comm.Parameters.AddWithValue("@qty", dataGridView2.Rows[i].Cells["7"].Value);
if (dataGridView2.Rows[i].Cells["BOOKCODE"].Value == null)
{
bookcode.Value = DBNull.Value;
}
if (dataGridView2.Rows[i].Cells["3"].Value == null)
{
barcode.Value = DBNull.Value;
}
if (dataGridView2.Rows[i].Cells["4"].Value == null)
{
desc.Value = DBNull.Value;
}
if (dataGridView2.Rows[i].Cells["5"].Value == null)
{
price.Value = DBNull.Value;
}
if (dataGridView2.Rows[i].Cells["6"].Value == null)
{
disc.Value = DBNull.Value;
}
// if (dataGridView2.Rows[i].Cells["7"].Value == null)
// {
// qty.Value = DBNull.Value;
// }
for (int q = 7; q <= dataGridView2.Columns.Count; q++) //dataGridView2.Columns.Count
{
int w = 1;
w++;
comm.Parameters.Add("@qty", SqlDbType.Int).Value = dataGridView2.Rows[w].Cells[q].Value;
comm.Parameters.Clear();
}
comm.ExecuteNonQuery();
comm.Parameters.Clear();
}
MessageBox.Show("Save SQL");
//try
//{
// comm.ExecuteNonQuery();
//}
//catch (Exception ex)
//{
// MessageBox.Show(ex.ToString());
//}
}
}
在您的for
循环中,您有:
comm.Parameters.Add("@qty", SqlDbType.Int).Value = dataGridView2.Rows[w].Cells[q].Value;
comm.Parameters.Clear();
因此,您在执行查询之前清除了之前添加的所有参数。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.