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

时间:2016-03-29 06:07:12

标签: c# .net winforms windows-applications

我正在尝试将记录插入到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();

        }

5 个答案:

答案 0 :(得分:3)

试试这个

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

答案 1 :(得分:2)

似乎是数据类型不匹配问题。检查数据表是否表格列是数字类型(例如:ERSBusinessLogic_ID是整数),那么代码应该像&#34; + Convert.ToInt32(dataGridView.Rows [i] .Cells [&#34; ERSBusinessLogic_ID&#34; ] .Value)+&#34;,

如果它是var-char类型,那么值应该是单引号(&#39;&#39;)之类的 &#39;&#34; + Convert.ToString(dataGridView.Rows [i] .Cells [&#34; ERSBusinessLogic_Formula&#34;]。Value)+&#34;&#39;,

答案 2 :(得分:0)

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

    }

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

答案 3 :(得分:0)

尝试添加&#39;&#39;到每个数据列。如下,

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

                        }

答案 4 :(得分:0)

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

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