2013-02-24 44 views
1

我正在将数据从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

您需要在SQL中以及在C#代码中引用任何字符串值引号。我假设这个ID是数字的,所以没有用单引号括起来。

string mysqlStatement = "INSERT INTO test1(Paper, Authors, ID, GSCitations) VALUES ('"+row.Cells[0]+"','"+row.Cells[1]+"',"+row.Cells[2]+",'"+row.Cells[3]+"');"; 
+0

现在通过2个引号,它帮助,异常消失了,thanx – mani1989 2013-02-24 14:30:36

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 + "');"; 
+0

你可以发布异常的堆栈跟踪? – levelnis 2013-02-24 14:26:47

相关问题