【问题标题】:How to insert records from data gridview entry to SQL database in C# windows application?如何在 C# windows 应用程序中将数据 gridview 条目中的记录插入 SQL 数据库?
【发布时间】:2016-03-29 06:07:12
【问题描述】:

我正在尝试将记录插入到 sql 数据库中,下面是我通过单击按钮进行插入的代码。

我无法插入记录,并且当我执行代码时它一直抛出错误.....我知道代码中有问题,但我不确定问题出在哪里。 ....

错误信息是“','.. 附近的语法不正确”

    private void ADD_button_Click(object sender, EventArgs e)
    {
        try
                    {
                        using (SqlConnection con = new SqlConnection(sqlconn))
                        {
                            con.Open();

                            for (int i = 1; i < dataGridView.Rows.Count; i++)
                            {
                                string sql = @"INSERT INTO ERSBusinessLogic VALUES ("
                                     + dataGridView.Rows[i].Cells["ERSBusinessLogic_ID"].Value + ", "
                                    + dataGridView.Rows[i].Cells["ERSBusinessLogic_Formula"].Value + ", "
                                    + dataGridView.Rows[i].Cells["ERSBusinessLogic_InputsCount"].Value + ", "
                                    + dataGridView.Rows[i].Cells["ERSBusinessLogic_Inputs"].Value + ");";

                                SqlCommand cmd = new SqlCommand(sql, con);
                                cmd.ExecuteNonQuery();

                            }
                        }
        }

        catch (Exception ex)
        {
            MessageBox.Show("Error : " + ex.Message);
        }
        finally
        {
            con.Close();

        }

【问题讨论】:

  • 显示错误信息,它是什么意思
  • 注意查询中所有输入的数据库表的数据类型:+ dataGridView.Rows[i].Cells["ERSBusinessLogic_ID"].Value + ", " + dataGridView.Rows[i].Cells ["ERSBusinessLogic_Formula"].Value + ", " + dataGridView.Rows[i].Cells["ERSBusinessLogic_InputsCount"].Value + ", " + dataGridView.Rows[i].Cells["ERSBusinessLogic_Inputs"].Value + ", " ");";它们必须匹配
  • 请检查我的编辑
  • 能否展示一下数据库表的结构?在数据库中的每个字符串字段周围,您需要在插入语句中添加一个“'”。
  • @diiN_(嗨......所以你的意思是如果数据类型是 varchar(例如:ERSbusinesslogic_inputs 是 varchar)......那么代码应该是“'”+ dataGridView.Rows[i]。单元格["ERSBusinessLogic_Inputs"].Value + " ' "

标签: c# .net winforms windows-applications


【解决方案1】:

试试这个

    private void button1_Click(object sender, EventArgs e)
    {
        // Getting data from DataGridView
        DataTable myDt = new DataTable();
        myDt = GetDTfromDGV(dataGridView1);

        // Writing to sql
        WriteToSQL(myDt);
    }

    private DataTable GetDTfromDGV(DataGridView dgv)
    {
        // Macking our DataTable
        DataTable dt = new DataTable();
        foreach (DataGridViewColumn column in dgv.Columns)
        {
            dt.Columns.Add(column.Name, typeof(string));
        }
        // Getting data
        foreach (DataGridViewRow dgvRow in dgv.Rows)
        {
            DataRow dr = dt.NewRow();
            for (int col = 0; col < dgv.Columns.Count; col++)
            {
                dr[col] = dgvRow.Cells[col].Value;
            }
            dt.Rows.Add(dr);
        }
        // removing empty rows
        for (int row = dt.Rows.Count - 1; row >= 0; row--)
        {
            bool flag = true;
            for (int col = 0; col < dt.Columns.Count; col++)
            {
                if (dt.Rows[row][col] != DBNull.Value)
                {
                    flag = false;
                    break;
                }
            }
            if (flag == true)
            {
                dt.Rows.RemoveAt(row);
            }
        }
        return dt;
    }
    private void WriteToSQL(DataTable dt)
    {
        string connectionStringSQL = "Your connection string";
        using (SqlConnection sqlConn = new SqlConnection(connectionStringSQL))
        {
            SqlBulkCopy sqlBulkCopy = new SqlBulkCopy(sqlConn);
            // Setting the database table name
            sqlBulkCopy.DestinationTableName = "Table_1_temp";
            // Mapping the DataTable columns with that of the database table
            sqlBulkCopy.ColumnMappings.Add(dt.Columns[0].ColumnName, "sql_col1");
            sqlBulkCopy.ColumnMappings.Add(dt.Columns[1].ColumnName, "sql_col2");
            sqlBulkCopy.ColumnMappings.Add(dt.Columns[2].ColumnName, "sql_col3");
            sqlBulkCopy.ColumnMappings.Add(dt.Columns[3].ColumnName, "sql_col4");
            sqlBulkCopy.ColumnMappings.Add(dt.Columns[4].ColumnName, "sql_col5");
            sqlBulkCopy.ColumnMappings.Add(dt.Columns[5].ColumnName, "sql_col6");
            sqlConn.Open();
            sqlBulkCopy.WriteToServer(dt);
        }
    }

【讨论】:

    【解决方案2】:

    这似乎是一个数据类型不匹配的问题。如果表列是数字类型(例如:ERSBusinessLogic_ID 是整数),请检查您的数据表,然后代码应类似于 "+Convert.ToInt32(dataGridView.Rows[i].Cells["ERSBusinessLogic_ID"].Value) + ",

    如果它是 var-char 类型,那么值应该是单引号('') '"+Convert.ToString(dataGridView.Rows[i].Cells["ERSBusinessLogic_Formula"].Value) + "',

    【讨论】:

      【解决方案3】:
          try
              {
               using (SqlConnection con = new SqlConnection(sqlconn))
               {
                 using (SqlCommand cmd = new SqlCommand())
                 {
                     cmd.Connection = con;
                     con.Open();
                     for (int i = 1; i < dataGridView.Rows.Count; i++)
                     {         
                      string sql = @"INSERT INTO ERSBusinessLogic VALUES ("
                                   +dataGridView.Rows[i].Cells["ERSBusinessLogic_ID"].Value + ", "
                                      + dataGridView.Rows[i].Cells["ERSBusinessLogic_Formula"].Value + ", "
                                      + dataGridView.Rows[i].Cells["ERSBusinessLogic_InputsCount"].Value + ", "
                                      + dataGridView.Rows[i].Cells["ERSBusinessLogic_Inputs"].Value + ");";
      
                                  cmd.CommandText = sql;
                                  cmd.ExecuteNonQuery();
      
                    }
               }
          }
      
          catch (Exception ex)
          {
              MessageBox.Show("Error : " + ex.Message);
          }
          finally
          {
              con.Close();
      
          }
      

      如果仍然不起作用,请在字符串后面放置一个断点,然后复制字符串值并在您的数据库上进行测试。也许你的价值观是问题,不同的类型。

      【讨论】:

      • 嗨,你是对的......我有空值也需要从网格视图中插入......但是该列不接受来自网格视图的空关键字...... ... 怎么做?
      • 如果在您的表格中被请求,也许您不应该允许在您的网格中添加空值。如果这些值可以为 null,则应将 db 列更改为接受 null。其他方式,我不知道
      【解决方案4】:

      尝试在每个数据列中添加 ''。如下,

      for (int i = 1; i < dataGridView.Rows.Count; i++)
                              {
                                  string sql = @"INSERT INTO ERSBusinessLogic VALUES ('"
                                       + dataGridView.Rows[i].Cells["ERSBusinessLogic_ID"].Value + "', '"
                                      + dataGridView.Rows[i].Cells["ERSBusinessLogic_Formula"].Value + "', '"
                                      + dataGridView.Rows[i].Cells["ERSBusinessLogic_InputsCount"].Value + "', '"
                                      + dataGridView.Rows[i].Cells["ERSBusinessLogic_Inputs"].Value + "');";
      
                                  SqlCommand cmd = new SqlCommand(sql, con);
                                  cmd.ExecuteNonQuery();
      
                              }
      

      【讨论】:

        【解决方案5】:

        祝你有美好的一天。您也可以尝试执行此选项。小心写下你的变量记录。

        using (SqlCommand cmd = new SqlCommand("INSERT INTO MyTable(Column1,Column2) VALUES (@Value1 @Value2)",con))
        cmd.Parameters.Add(newSqlParameter("@Value1",SqlDbType.VarChar));
        cmd.Parameters.Add(newSqlParameter("@Value2",SqlDbType.VarChar));
        con.Open();
            foreach (DataGridViewRow row in myDataGridView.Rows)
                {
                if (!row.IsNewRow)
                    {
                    cmd.Parameters["@C1"].Value = row.Cells[0].Value;
                    cmd.Parameters["@C2"].Value = row.Cells[1].Value;
                    cmd.ExecuteNonQuery();
                    }
                }
            }
        }
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2022-11-27
          • 2013-12-04
          • 1970-01-01
          • 2018-05-07
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多