2014-07-03 97 views
0

我想下面的代碼:無法插入一排參數

try 
{ 
    SqlConnection conn = new SqlConnection("server=ARSLAN-LAPI\\SQLEXPRESS;" + 
         "Trusted_Connection=yes;" + 
         "database=OTTS; " + 
         "connection timeout=30"); 
    conn.Open(); 
    String name=UserName.Text; 
    String pwd=Password.Text; 
    String query = "INSERT INTO dbo.user (username,password) 
        VALUES(@username,@password)"; 
    SqlCommand command = new SqlCommand(query, conn); 
    command.Parameters.Add("@username",name); 
    command.Parameters.Add("@password",pwd); 
    command.ExecuteNonQuery(); 
    conn.Close(); 
    ErrorMessage.Text="Well done!"; 
} 
catch(SqlException ex) 
{ 
    ErrorMessage.Text="You failed!" + ex.Message; 
} 

收到錯誤

You failed!Incorrect syntax near the keyword 'user'.

請指導我..

回答

0

User is a reserved keyword,我強烈建議將該字段名稱更改爲不同的內容。
但是,如果您仍然堅持使用它,請記住在每次需要時將其括在方括號中。

string query = "INSERT INTO [dbo].[user] (username,password) VALUES(@username,@password)"; 
0

試試這個:

INSERT INTO dbo.[user] (username,password) VALUES(@username,@password) 
+0

雖然正確,你應該解釋更多。 – DavidG

0

嘗試這樣的事情,

SqlCommand command = new SqlCommand(query, conn); 
command.Parameters.Add("@username",SqlDbType.VarChar,50).Value = name; 
command.Parameters.Add("@password",SqlDbType.VarChar,50).Value= pwd; 
command.ExecuteNonQuery();