SQL error: Incorrect syntax near the keyword '

2020-01-24 13:20发布

问题:

I am using SQL to insert data to SQL Database file using C# as follows.

    String cs = System.Configuration.ConfigurationManager.ConnectionStrings["connection1"].ConnectionString;
    SqlConnection conn = new SqlConnection(cs);
    String sql = "INSERT INTO User (login, password, status) " + 
            "VALUES (@login, @password, @status)";
    SqlCommand comm = new SqlCommand(sql, conn);

    comm.Parameters.Add("@login", System.Data.SqlDbType.VarChar);
    comm.Parameters.Add("@password", System.Data.SqlDbType.VarChar);
    comm.Parameters.Add("@status", System.Data.SqlDbType.Bit);

    try
    {
        conn.Open();
        Console.WriteLine(conn.ToString());
        comm.ExecuteNonQuery();
        conn.Close();
        return true;
    }
    catch (Exception ex)
    {
        throw (ex);
    }
    finally
    {
        conn.Close();
    }

I am getting the following error when command is executing.

Incorrect syntax near the keyword 'User'.: INSERT INTO User (login, password, status) VALUES (@login, @password, @status)

How can I solve this please?

edit: missed parameter values added..

    comm.Parameters["@login"].Value = this.Username;
    comm.Parameters["@password"].Value = this._password;
    comm.Parameters["@status"].Value = this.Status;

回答1:

User is a reserved keyword, so you must use square brackets to make it explicit that you mean the object named "User" it, i.e. use [User] instead of User.



回答2:

User is a t-sql reserved keyword. Enclosing it in square brackets should solve this. E.g INSERT INTO [User]



回答3:

run your query against the database. You can use the declare sql keyword to define your variables and give them values. If you need to figure out the variables values, set a breakpoint at conn.Open and then use the locals window to see what values you are passing in. Another tool at your disposal is the Sql Profiler. You can start a trace then run your program. You should be able to see the query as executed in the profile after the code you have posted has run.

All of this should help you to figure out what is wrong with your sql when the exception does not provide enough information.

The Sql Server Management Studio should have highlighted the User keyword in your sql statement, easily showing that you need brackets around it like so: [User]



回答4:

User is a sql reserved keyword. Enclosing it in square brackets should solve this. E.g INSERT INTO [User]

easily showing that you need brackets around it like so: [User]