这是我的代码:
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'中插入重复键。重复键值为()。
答案 0 :(得分:0)
问题:您只检查null和Empty,但您没有检查Whitespace
。
解决方案:您还需要检查Whitespace
。如果你使用String.IsNullOrWhiteSPace(),它将检查Null,Empty和Whitespace。
试试这个:
if(!String.IsNullOrWhiteSpace(textBox1.Text) || !String.IsNullOrWhiteSpace(textBox2.Text))
建议:
确认INSERT成功与否的最佳方法是检查return
方法的ExecuteNonQuery()
值。
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...");
}
}