从Windows窗体将值插入SQL数据库时出现不正确的语法错误

时间:2018-06-30 14:04:36

标签: c# sql-server

我想将Windows Form应用程序与SQL Server连接起来,并将值从应用程序文本框中插入数据库。单击按钮后,我收到错误消息:

  

关键字“组”附近的语法不正确。

出什么问题了?如何插入这些数据?

 private void button1_Click(object sender, EventArgs e)
    {

        try
        {
            string myconnection = @"Data Source=(localdb)\MSSQLLocalDB;Initial Catalog=StudBase;Integrated Security=True";
            string Query = "Insert Into StudentInfo (StudentID, Name,Surname,Group,Course,City,Sector,Average rating) values('" +this.textBox1.Text+"','" + this.textBox2.Text + "','" + this.textBox4.Text + "','" + this.textBox6.Text + "','" + this.textBox8.Text + "','" + this.textBox3.Text + "','" + this.textBox5.Text + "','" + this.textBox3.Text + "');";

            SqlConnection Myconn = new SqlConnection(myconnection);
            SqlCommand Mycom = new SqlCommand(Query, Myconn);
            SqlDataReader Reader1;
            Myconn.Open();
            Reader1 = Mycom.ExecuteReader();
            MessageBox.Show("Save data");
            while (Reader1.Read())
            {

            }
            Myconn.Close();
        }
        catch (Exception ex)
        {
            MessageBox.Show(ex.Message);
        }


    }

enter image description here

1 个答案:

答案 0 :(得分:-1)

将其用于您的查询语句-

string Query = "Insert Into StudentInfo (StudentID,[Name],Surname,[Group],Course,City,Sector,[Average rating]) values('" +this.textBox1.Text+"','" + this.textBox2.Text + "','" + this.textBox4.Text + "','" + this.textBox6.Text + "','" + this.textBox8.Text + "','" + this.textBox3.Text + "','" + this.textBox5.Text + "','" + this.textBox3.Text + "');";

对SQL中的保留关键字使用[]。另外,最后一列平均评分没有用[]覆盖,因为此列名称具有空格,因此应在[]中引用。