2014-01-22 38 views
1

這是我的代碼:問題在登記表格的Visual Studio SQL Server數據庫

private void button1_Click(object sender, EventArgs e) 
{ 
      SqlConnection con = new SqlConnection(@"Data Source=(LocalDB)\v11.0;AttachDbFilename=C:\Users\Dido\Documents\DataCars.mdf;Integrated Security=True;Connect Timeout=30"); 
      SqlCommand cmd = new SqlCommand("insert into Login values('" + textBox1.Text + "','" + textBox2.Text + "')", con); 

      con.Open(); 
      cmd.ExecuteNonQuery(); 
      con.Close(); 

      if (!String.IsNullOrEmpty(textBox1.Text) || !String.IsNullOrEmpty(textBox2.Text)) 
      { 
       MessageBox.Show("Your registration was successfull!"); 
       Login frm1 = new Login(); 
       Global.GlobalVar = textBox1.Text; 
       frm1.Show(); 
       this.Hide(); 
      } 
      else 
      { 
       MessageBox.Show("Please insert some text..."); 
      } 
     } 

當我試圖註冊的用戶名和密碼的用戶 - 它說,這是成功的,但唯一的事情,在數據庫中添加的是一個空行。當我剛上的「註冊」按鈕,單擊不寫東西,整個事情打破了這個錯誤出現:

PRIMARY KEY約束違反「PK_ 登錄 _536C85E5BD4FE4C6」。不能在對象'dbo.Login'中插入重複鍵。重複的鍵值是()。

+2

請始終使用['參數queries'(http://www.codinghorror.com/blog/2005/04/give-me-parameterized- SQL-或放棄的我,death.html)。這種字符串連接對[SQL注入](http://en.wikipedia.org/wiki/SQL_injection)攻擊是開放的。 –

+0

流程看起來不正確:您應該在嘗試更新數據庫之前檢查String.IsNullOrEmpty嗎? – richaux

+0

哦,謝謝你,那工作! – Cathy

回答

0

問題:你只檢查空和空,但你不檢查Whitespace

解決方案:您還需要檢查Whitespace。如果使用String.IsNullOrWhiteSPace(),它將檢查Null,Empty和Whitespace。

試試這個:

if(!String.IsNullOrWhiteSpace(textBox1.Text) || !String.IsNullOrWhiteSpace(textBox2.Text)) 

建議:

最好的方式來確認羯羊INSERT是全成與否檢查ExecuteNonQuery()方法的return值。

int Status=cmd.ExecuteNonQuery(); 
if(STatus>0) 
MessageBox.Show("Your registration was successfull!"); 
else 
MessageBox.Show("Please insert some text..."); 

完整代碼:

private void button1_Click(object sender, EventArgs e) 
{ 
    if(!String.IsNullOrWhiteSpace(textBox1.Text) || !String.IsNullOrWhiteSpace(textBox2.Text)) 
    { 
     SqlConnection con = new SqlConnection(@"Data Source=(LocalDB)\v11.0;AttachDbFilename=C:\Users\Dido\Documents\DataCars.mdf;Integrated Security=True;Connect Timeout=30"); 
     SqlCommand cmd = new SqlCommand("insert into Login values('" + textBox1.Text + "','" + textBox2.Text + "')", con); 

     con.Open(); 
     int Status=cmd.ExecuteNonQuery(); 
     con.Close(); 
     if(Status>0) 
     { 
      MessageBox.Show("Your registration was successfull!"); 
      Login frm1 = new Login(); 
      Global.GlobalVar = textBox1.Text; 
      frm1.Show(); 
      this.Hide(); 
     } 
     else 
     { 
      MessageBox.Show("no records updated!"); 
     } 
     } 
     else 
     { 
      MessageBox.Show("Please insert some text..."); 
     } 
} 
+0

非常感謝! – Cathy

+0

@Cathy:歡迎您,很高興爲您服務。 –

相關問題