如何在 C# windows 应用程序中将数据 gridview 条目中的记录插入到 SQL 数据库?

How to insert records from data gridview entry to SQL database in C# windows application?

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

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

错误信息是"Incorrect syntax near ','.. "

    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();

        }
    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();

    }

如果还是不行,就在字符串后面打个断点,复制字符串值到你的数据库上测试。可能是你的价值观有问题,不同类型。

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

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();

                        }

似乎是数据类型不匹配的问题。检查你的数据 table 如果 table 列是数字类型(例如:ERSBusinessLogic_ID 是整数)那么代码应该像 "+Convert.ToInt32(dataGridView.Rows[i] .Cells["ERSBusinessLogic_ID"].Value) + ",

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

试试这个

    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);
        }
    }

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

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();
            }
        }
    }
}