无法插入带参数的行

时间:2014-07-03 07:49:34

标签: c# sql-server visual-studio sql-server-2012

我正在尝试以下代码:

try
{
    SqlConnection conn = new SqlConnection("server=ARSLAN-LAPI\\SQLEXPRESS;" +
                         "Trusted_Connection=yes;" +
                         "database=OTTS; " +
                         "connection timeout=30");
    conn.Open();
    String name=UserName.Text;
    String pwd=Password.Text;
    String query = "INSERT INTO dbo.user (username,password) 
                     VALUES(@username,@password)";
    SqlCommand command = new SqlCommand(query, conn);
    command.Parameters.Add("@username",name);
    command.Parameters.Add("@password",pwd);
    command.ExecuteNonQuery();
    conn.Close();
    ErrorMessage.Text="Well done!";
}
catch(SqlException ex)
{
     ErrorMessage.Text="You failed!" + ex.Message;
}

收到错误

You failed!Incorrect syntax near the keyword 'user'.

请指导我..

3 个答案:

答案 0 :(得分:0)

User is a reserved keyword,我强烈建议将该字段名称更改为不同的字段 但是,如果您仍然坚持使用它,请记住每次需要时将其括在方括号中。

string query = "INSERT INTO [dbo].[user] (username,password) VALUES(@username,@password)";

答案 1 :(得分:0)

试试这个:

INSERT INTO dbo.[user] (username,password)   VALUES(@username,@password)

答案 2 :(得分:0)

尝试这样的事情,

SqlCommand command = new SqlCommand(query, conn);
command.Parameters.Add("@username",SqlDbType.VarChar,50).Value = name;
command.Parameters.Add("@password",SqlDbType.VarChar,50).Value= pwd;
command.ExecuteNonQuery();