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();
使用上面的代码我得到“语法错误near =”错误。我做错了什么?
答案 0 :(得分:6)
您需要更改INSERT语句的语法:
INSERT INTO [Users] (UserName, FirstName, ...)
SELECT @UserName, @firstname, ...
上的文档
最好明确列出您将INSERT INTO
列的列。如果修改了表的列顺序,这可以防止任何(可能很难解决)问题。这可能导致INSERT
失败(插入无效类型),或者将值插入意外列(重新排序列,但它们具有相同的类型,因此插入将成功)
答案 1 :(得分:4)
在INSERT语句中,不要使用Username = @ username等,因为这不是有效的SQL。它看起来应该是这样的:
command.CommandText = "INSERT INTO [Users] VALUES (@username, @firstname, @lastname, NULL, @bio, @email, @emailverified, @hash, @companyid)";
这假设值的顺序与数据库中的列的顺序相同,否则您也需要指定列。