2015-07-01 23 views
1
con.Open(); 
     cmd = new OleDbCommand("insert into login (user, password) values ('" +textBox1 .Text + "','" + textBox2 .Text + "');",con); 
     cmd.CommandType = CommandType.Text; 
     int temp = cmd.ExecuteNonQuery(); 
     if (temp > 0) 
     { 
      textBox1.Text = null; 
      textBox2.Text = null; 
      MessageBox.Show("Record Successfuly Added"); 
     } 
     else 
     { 
      MessageBox.Show("Record Fail to Added"); 
     } 
     con.Close(); 

當我嘗試插入一些錯誤的出現(語法錯誤在INSERT語句) 我敢嘗試不同的方法來像的參數或直接 PLZ值!語法錯誤從C#到Access數據庫

+1

我認爲這是因爲像「登錄」,「用戶」這樣的關鍵詞'password',嘗試在它們周圍放置方括號'[]'並再次執行相同的查詢。 –

+0

正如@ M.Ali指出的,[用戶是保留字](https://support.microsoft.com/en-us/kb/248738) – stuartd

+0

備註:** 1)**使用'textBox1.Text = string.Empty'而不是'textBox1.Text = null'。 ** 2)**可以在查詢執行後立即關閉連接('int temp = cmd.ExecuteNonQuery(); con.Close();')。 –

回答

1
  • 逃生保留關鍵字user
  • 使用參數化查詢
  • 避免SQL注入
  • 製作使用一次性物品的

試試這個辦法:

using (OleDbConnection con = new OleDbConnection(connectionString)) 
{ 
    con.Open(); 
    using (var cmd = new SqlCommand(
    "insert into login ([user], [password]) values (@user, @pass);", 
    con)) 
    { 
     cmd.Parameters.Add(new OleDbParameter("@user", textBox1.Text)); 
     cmd.Parameters.Add(new OleDbParameter("@pass", textBox1.Text)); 

     if (temp > 0) 
     { 
      textBox1.Text = String.Empty; 
      textBox2.Text = String.Empty; 
      MessageBox.Show("Record Successfuly Added"); 
     } 
     else 
     { 
      MessageBox.Show("Record Fail to Added"); 
     } 
    } 
} 
+0

歡迎您接受我的回答 – meda

+0

我該怎麼辦? 我是這個網站的新用戶 –

+0

@ Dev.Mahmood檢查這個http://meta.stackexchange.com/questions/5234/how-does-accepting-an-answer-work/5235#5235 – meda