【问题标题】:Adding data in sql Table在sql表中添加数据
【发布时间】:2014-06-06 00:09:28
【问题描述】:

我有这个基本的 WinForms 应用程序用户界面:

当单击“Gem”按钮时,我想将数据同时添加到 DataGridView 和 sql 表中。我有以下代码:

private void Form2_Load(object sender, EventArgs e)
    {
        try
        {
            con = new SqlConnection();
            con.ConnectionString = @"Data Source=(LocalDB)\v11.0;AttachDbFilename=|DataDirectory|\Produkt.mdf;Integrated Security=True";
            con.Open();
            //adap = new SqlDataAdapter("select SN, FName as 'Navn', MName as 'Vare nr', LName as 'Antal', Age from Produkt", con);
            string sql = "SELECT Navn, Varenr, Antal, Enhed, Priseksklmoms, Konto FROM ProduktTable";

            adap = new SqlDataAdapter(sql, con);
            ds = new System.Data.DataSet();
            adap.Fill(ds, "ProduktTable");
            dataGridView1.DataSource = ds.Tables["ProduktTable"];

        }

        catch (Exception ex)
        {
            MessageBox.Show("Error\n" + ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
        }

    }

private void button1_Click(object sender, EventArgs e)
    {
        string navn = textBox2.Text;
        int varenr = int.Parse(textBox3.Text);
        float antal = (float)Convert.ToDouble(textBox4.Text);
        string enhed = textBox5.Text;
        string konto = comboBox2.Text;
        float pris = (float)Convert.ToDouble(textBox6.Text);

        dataGridView1.Rows[0].Cells[0].Value = navn;
        dataGridView1.Rows[0].Cells[1].Value = varenr;

        string StrQuery;

        try
        {

            SqlCommand comm = new SqlCommand();
            comm.Connection = con;

           for (int i = 0; i < dataGridView1.Rows.Count; i++)
            {
                StrQuery = @"INSERT INTO ProduktTable VALUES ('"
                + dataGridView1.Rows[i].Cells[0].Value + "',' "
                + dataGridView1.Rows[i].Cells[1].Value + "');";
                comm.CommandText = StrQuery;                  
                comm.ExecuteNonQuery();                    
            }

        }
        catch (Exception ex)
        {
            MessageBox.Show("Error\n" + ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
        }

这只是一个示例,目的是在 DataGridView 和 sql 中存储字符串“navn”和整数“Varenr”。当我运行应用程序并单击按钮时,出现以下错误:

我的 ProduktTable 表的列名与 dataGridView 的列名完全相同。

提前致谢

【问题讨论】:

  • 您是否尝试在 for 语句上设置断点来检查循环是否超出数据库字段的范围?
  • 是的。它在第一次到达 comm.ExecuteNonQuery() 行时抛出错误。
  • 停止将您的 SQL 语句连接在一起!这是一个巨大的安全风险,并为 SQL 注入攻击打开了大门!只是不要这样做 - 永远。相反,使用参数化查询 - 总是,没有例外

标签: c# sql sql-server-2012-express


【解决方案1】:

在插入语句中显式设置列名...

StrQuery = @"INSERT INTO ProduktTable (Navn, Varenr) VALUES ('"
                + dataGridView1.Rows[i].Cells[0].Value + "',' "
                + dataGridView1.Rows[i].Cells[1].Value + "');";

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-09-21
    • 1970-01-01
    • 1970-01-01
    • 2012-08-24
    • 1970-01-01
    相关资源
    最近更新 更多