【问题标题】:Adding data in sql Table columns在sql表列中添加数据
【发布时间】:2014-06-05 20:25:13
【问题描述】:

我有这个基本的 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 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);
        }

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

程序有什么问题?

提前致谢

【问题讨论】:

  • INSERT INTO tableName ProduktTable 为什么会有tableName这个词?解析器认为这是您的表名,因此 ProduktTable 是语法错误。
  • 您不必在插入语句中提及 tableName

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


【解决方案1】:

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

INSERT INTO tableName ProduktTable

应该是

INSERT INTO ProduktTable

假设 Produ**K**tTable 不是错字。

【讨论】:

  • @marc_s 好的。我不确定这是否是一个错字。那么问题应该只是表格名称。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-06-15
  • 1970-01-01
  • 2020-06-27
相关资源
最近更新 更多