将数据插入数据库但出现不正确的语法错误

时间:2019-05-30 03:05:00

标签: c#

我正在尝试将学生数据添加到数据库中,但不断出现错误“关键字'Table'附近的语法不正确”。我对使用Windows窗体很陌生,有人知道我哪里出错了吗?

private void BTAddstudent_Click(object sender, EventArgs e)
{
    try
    {
        string myconnection = @"Data Source = (LocalDB)\MSSQLLocalDB; AttachDbFilename = C:\Users\tayla\OneDrive\Documents\StudentPerformance\StudentPerformance\Studentdatabase.mdf; Integrated Security = True";

        string Query = "Insert Into Table (ID, First name, Last name, Course 1, Course 2, Course 3, Course 4, Course 5, Course 6, Course 7, Course 8, Course 9, Course 10) values('" + this.txtbxID.Text + "','" + this.txtbxfirstname.Text + "','" + this.txtbxlastname.Text + "','" + this.txtbxcourse1.Text
            + "','" + this.txtbxcourse2.Text + "','" + this.txtbxcourse3.Text + "','" + this.txtbxcourse4.Text + "','" + this.txtbxcourse5.Text + "','" + this.txtbxcourse6.Text + "','" + this.txtbxcourse7.Text
            + "','" + this.txtbxcourse8.Text + "','" + this.txtbxcourse9.Text + "','" + this.txtbxcourse10.Text + "')";

        SqlConnection myconn = new SqlConnection(myconnection);
        SqlCommand mycom = new SqlCommand(Query, myconn);
        SqlDataReader reader1;
        myconn.Open();
        reader1 = mycom.ExecuteReader();
        while (reader1.Read()) ;
        {
        }
        myconn.Close();
    }
    catch (Exception ex)
    {
        MessageBox.Show(ex.Message);
    }
}

1 个答案:

答案 0 :(得分:1)

如果您将表命名为[STEP 101] # cat foo.exp #!/usr/bin/expect set ps_re "> $" spawn -noecho bash --noprofile --norc expect bash send "PS1='> '\r" expect -re $ps_re for { set i 10 } { $i < 15 } { incr i } { send "echo $i\r" expect -re ".*\\r\\n(\[0-9]+)\\r\\n$ps_re" } send "exit\r" expect eof [STEP 102] # expect foo.exp bash-5.0# PS1='> ' > echo 10 10 > echo 11 11 > echo 12 12 > echo 13 13 > echo 14 14 > exit exit [STEP 103] # ,则必须使用方括号,因为Table是保留字。如果使用空格,则还必须在列名称中使用方括号。

您的sql语句应如下所示:

Table

使用参数化查询更好。它更易于阅读,并且可以防止SQL注入攻击。