简体   繁体   English

“'='附近的语法不正确”运行时错误C#asp.net

[英]“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语句的语法:

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

Documentation on the INSERT syntax 有关INSERT语法的文档

It is considered better practice to explicitly list out the columns you will INSERT INTO . 最好将要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) 这可能会导致您的INSERT失败(插入无效类型),或者将值插入意外列(对列进行重新排序,但是它们具有相同的类型,因此插入将成功)

In your INSERT statement do not use Username=@username etc, because that is not valid SQL. 在您的INSERT语句中,请勿使用Username = @ username等,因为这是无效的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. 这假定值的顺序与数据库中列的顺序相同,否则,您也需要指定列。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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