0

我在数据库中有一个表,其中作者姓名与他们的谷歌引文一起存储。多个作者用逗号分隔。我使用以下代码将它们拆分并在数据网格视图中显示:

foreach (DataRow row in dataTable.Rows)
{
   int GSCitations;
   {
        string paper = Convert.ToString(row[1]);
        Int32.TryParse(Convert.ToString(row[2]), out GSCitations);
        string str = Convert.ToString(row[0]);
        string[] result = str.Split(new Char[] { ',' });
        foreach (string author in result)
        {
            dataGridView1.Rows.Add(id, author, paper, GSCitations);
            id++;
        }

   }

然后我从数据网格视图中选择它们并尝试使用以下代码将它们存储在数据库中:

foreach (DataGridViewRow row in dataGridView1.Rows)
 {
        try
         {
         mysqlStatement = "INSERT INTO test1(ID, Authors,Paper, GSCitations) VALUES('" + row.Cells[0].Value + "','" + row.Cells[1].Value + "','" + row.Cells[2].Value + "','" + row.Cells[3].Value +"');";
         mySqlCommand = new MySqlCommand(mysqlStatement, mySqlConnection);
         mySqlCommand.ExecuteNonQuery();     
         }

        catch(Exception excep)
        {
         MessageBox.Show(excep.ToString()); 
        }
  }

但它抛出异常,该 id 为空。由于 id 是主键,它不能为空。在数据网格视图中,没有 id 为空,但在存储它时返回空 id,就在一组作者被拆分之后。我的意思是,如果第一篇论文是由四位作者撰写的。它在 4 行之后立即返回 null,然后在每组之后以此类推。请帮忙

4

2 回答 2

1

需要正确调试代码并查看完整代码以给出这种行为的确切原因,但如果你只是想让它工作,试试这个

foreach (DataGridViewRow row in dataGridView1.Rows)
 {
        if(row == null || row.Cells[0].Value == null)
           continue;

        try
         {
            mysqlStatement = "INSERT INTO test1(ID, Authors,Paper, GSCitations) VALUES('" + row.Cells[0].Value + "','" + row.Cells[1].Value + "','" + row.Cells[2].Value + "','" + row.Cells[3].Value +"');";
            mySqlCommand = new MySqlCommand(mysqlStatement, mySqlConnection);
            mySqlCommand.ExecuteNonQuery();     
         }

        catch(Exception excep)
        {
            MessageBox.Show(excep.ToString()); 
        }
  }
于 2013-03-18T05:57:20.173 回答
0

尝试将您的单元格 [索引] 更改为单元格 [列名],我猜索引是您的 ID 列返回 null 的原因

mysqlStatement = "INSERT INTO test1(ID, Authors,Paper, GSCitations) 
VALUES('" +row.Cells[YOUR COLUMN NAME].Value + "','" + 
row.Cells[YOUR COLUMN NAME].Value + "','" + 
row.Cells[YOUR COLUMN NAME].Value + "','" + 
row.Cells[YOUR COLUMN NAME].Value +"');";
于 2013-03-18T05:51:21.957 回答