這是我的代碼:問題在登記表格的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'中插入重複鍵。重複的鍵值是()。
請始終使用['參數queries'(http://www.codinghorror.com/blog/2005/04/give-me-parameterized- SQL-或放棄的我,death.html)。這種字符串連接對[SQL注入](http://en.wikipedia.org/wiki/SQL_injection)攻擊是開放的。 –
流程看起來不正確:您應該在嘗試更新數據庫之前檢查String.IsNullOrEmpty嗎? – richaux
哦,謝謝你,那工作! – Cathy