我正在处理插入语句,其中需要从 gridview 抓取数据并将其保存在表中插入 3 个值,但是“关键字参数值正在逐字更新,就像数据库中的 @Keyword 一样”,但其他值变得很好。
代码如下
using (SqlCommand com = new SqlCommand("INSERT INTO PositionsTable (Id,Keyword,Position) VALUES (@Id,'@Keyword',@Position)", con))
{
com.Parameters.AddWithValue("@Keyword", SqlDbType.VarChar);
com.Parameters.AddWithValue("@Position", SqlDbType.Int);
com.Parameters.AddWithValue("@Id", SqlDbType.Int);
for (int i = 0; i < dataGridView1.Rows.Count; i++)
{
string keywordCell = dataGridView1.Rows[i].Cells["Keywords"].Value.ToString();
int positionCell = Convert.ToInt16(dataGridView1.Rows[i].Cells["Position"].Value);
com.Parameters["@Keyword"].Value = keywordCell;
com.Parameters["@Position"].Value = positionCell;
com.Parameters["@Id"].Value = count;
com.ExecuteNonQuery();
}
}
我在调试时测试了 keywordCell 变量成功地从 gridview 获取值,就像 positionCell 但它在数据库中更新了“@Keyword”,其中 positionCell 已正确更新。
你能指出我哪里做错了吗?
最佳答案
你在 SQL 语句中用引号将关键字括起来
改变
"INSERT INTO PositionsTable (Id,Keyword,Position) VALUES (@Id,'@Keyword',@Position)"
到
"INSERT INTO PositionsTable (Id,Keyword,Position) VALUES (@Id,@Keyword,@Position)"
关于c# - 一个参数值按字面意思更新,但其他参数值正常 C#,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32606961/