在sql表列中添加数据

时间:2014-06-05 20:25:14

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

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

enter image description here

我希望将数据添加到DataGridView和sql表中,当" Gem"单击按钮。我有以下代码:

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 tableName ProduktTable ("
                + dataGridView1.Rows[i].Cells["Varenr"].Value + ", "
                + dataGridView1.Rows[i].Cells["Antal"].Value + ");";
                comm.CommandText = StrQuery;
                comm.ExecuteNonQuery();                    
            }

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

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

enter image description here

手术有什么问题?

提前致谢

1 个答案:

答案 0 :(得分:1)

插入名称的格式不需要单词tableName。它需要实际的表名。

INSERT INTO tableName ProduktTable

应该是

INSERT INTO ProduktTable

假设Produ ** K ** tTable不是拼写错误。