1

我正在将数据从 a 复制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();
}
4

2 回答 2

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 + "');";
于 2013-02-24T14:18:46.283 回答
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]+"');";
于 2013-02-24T14:21:40.327 回答