我正在将数据从DataGridView
复制到数据库表名test1,但是正在引发无效操作异常。我该如何解决这个问题?
foreach (DataGridViewRow row in dataGridView2.Rows)
{
string mysqlStatement = "INSERT INTO test1(Paper, Authors, ID, GSCitations)VALUES("+row.Cells[0]+","+row.Cells[1]+","+row.Cells[2]+","+row.Cells[3]+");";
MySqlCommand mysqlCmd = new MySqlCommand(mysqlStatement, connection);
mysqlCmd.ExecuteNonQuery();
}
答案 0 :(得分:0)
首先,你有一个拼写错误,在VALUES
之前放置空格。
然后,根据编写的列,我认为您有varchar
个数据类型,您应该将它们的值放在引号之间。不知何故喜欢这个
string mysqlStatement = "INSERT INTO test1(Paper, Authors, ID, GSCitations)
VALUES('" + row.Cells[0].Value + "','" + row.Cells[1].Value + "',"
+ row.Cells[2].Value + ",'" + row.Cells[3].Value + "');";
答案 1 :(得分:0)
您需要将任何字符串值括在SQL中以及C#代码中的引号中。我假设该ID是数字的,所以没有将单元格2括在引号中。
string mysqlStatement = "INSERT INTO test1(Paper, Authors, ID, GSCitations) VALUES ('"+row.Cells[0]+"','"+row.Cells[1]+"',"+row.Cells[2]+",'"+row.Cells[3]+"');";