1
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?

1
  • 4
    Read up on the insert sql statement. Your syntax is wrong. Just list the parameters in the order they are in the table, don't have the ColumnName= part. Commented Nov 21, 2011 at 16:48

2 Answers 2

6

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)

Sign up to request clarification or add additional context in comments.

Comments

4

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.