执行SQL Server INSERT时出现未处理的异常

时间:2018-02-25 09:54:33

标签: c# sql-server

我已用C#编写代码并将其与SQL Server集成,但每次运行时我都会收到此错误:

  

System.Data.SqlClient.SqlException:'语法不正确';'。'

我的代码是:

private void btnsubmit_Click(object sender, EventArgs e)
{
    var connectiontring =
        ConfigurationManager.ConnectionStrings["connData"].ConnectionString;

    string querystring = "INSERT INTO [Table] VALUES(@Name, @Gender, @Age, @Course, @Department, @Program, @Address, @PostCode, @Email;";

    using (var connection = new SqlConnection(connectiontring))
    {
        var cmd = new SqlCommand(querystring, connection);
        connection.Open();

        cmd.Parameters.AddWithValue("Name", tblName.Text);
        ...
        cmd.Parameters.AddWithValue("Email", tbllMail.Text);

        cmd.ExecuteReader();

        tblName.Text = "";
        ...
        tbllMail.Text = "";
    }
}

2 个答案:

答案 0 :(得分:3)

SQL Server是对的。在值列表后添加结束表:

string querystring = "insert into [Table] VALUES(@Name, ..., @Email);";

答案 1 :(得分:2)

您的查询字符串中有一个;,其中应显示)。正确的查询字符串是:

 string querystring = 
    "insert into [Table] VALUES " +
    "   (@Name, @Gender, @Age, @Course, @Department, @Program, " +
    "    @Address, @PostCode, @Email)";