2011-11-21 63 views
1
SqlConnection sqlConnection = new SqlConnection(sqlConnectionString); 
SqlCommand command = new SqlCommand(); 

command.CommandText = 
    "INSERT INTO [Users] 
    VALUES ([email protected], [email protected] 
      , [email protected], ProfilePic=NULL, [email protected], [email protected] 
      , [email protected], [email protected], [email protected])"; 
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(); 

通過上面的代碼,我得到「Syntax error near =」錯誤。我做錯了什麼?「不正確的語法附近'='」運行時錯誤c#asp.net

+4

閱讀關於insert sql語句。你的語法錯了。只需按照它們在表中的順序列出參數,不要有'ColumnName ='部分。 –

回答

4

在您的INSERT語句中,不要使用Username = @ username等,因爲這不是有效的SQL。它應該是這樣的,而不是:

這是假設值是相同的順序在數據庫中的列,否則你將需要太指定列。

6

你需要改變你的INSERT語句的語法:

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

文檔上INSERT syntax

它被認爲是更好的做法是明確地列出列你會INSERT INTO。如果您的表的列順序被修改,這可以防止任何(可能難以排除故障)問題。這可能會導致您的INSERT失敗(插入到無效類型中)或將值插入意外列(重新排序列,但它們具有相同類型,因此插入操作將成功)

相關問題