简体   繁体   中英

“Incorrect syntax near '='” runtime error c# asp.net

SqlConnection sqlConnection = new SqlConnection(sqlConnectionString);
SqlCommand command = new SqlCommand();

command.CommandText = 
   "INSERT INTO [Users] 
    VALUES (Username=@username, Firstname=@firstname
          , Lastname=@lastname, ProfilePic=NULL, Bio=@bio, Email=@email
          , EmailIsVerified=@emailverified, Hash=@hash, CompanyID=@companyid)";
command.Parameters.AddWithValue("@username", m_username);
command.Parameters.AddWithValue("@firstname", m_firstname);
command.Parameters.AddWithValue("@lastname", m_lastname);
command.Parameters.AddWithValue("@bio", m_bio);
command.Parameters.AddWithValue("@email", m_email);
command.Parameters.AddWithValue("@emailverified", (m_emailIsVerified ? "yes" : "no"));
command.Parameters.AddWithValue("@hash", m_hash);
command.Parameters.AddWithValue("@companyid", m_companyID);
command.CommandType = CommandType.Text;
command.Connection = sqlConnection;

sqlConnection.Open();

command.ExecuteNonQuery();

sqlConnection.Close();

With the above code I get the "Syntax error near =" error. What have I done wrong?

You need to change your INSERT statement's syntax:

INSERT INTO [Users] (UserName, FirstName, ...)
SELECT @UserName, @firstname, ...

Documentation on the INSERT syntax

It is considered better practice to explicitly list out the columns you will INSERT INTO . This prevents any (potentially difficult to troubleshoot) issues if the column order of your table is modified. This could cause your INSERT to either fail (inserting into invalid types), or insert values into unexpected columns (re-order columns, but they have the same type, so the insert will succeed)

In your INSERT statement do not use Username=@username etc, because that is not valid SQL. It should look like this instead:

command.CommandText = "INSERT INTO [Users] VALUES (@username, @firstname, @lastname, NULL, @bio, @email, @emailverified, @hash, @companyid)"; 

This assumes the values are in the same order as the columns in the database, otherwise you will need to specify the columns too.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM