繁体   English   中英

注册表单Visual Studio中的SQL Server数据库问题

[英]Issue with SQL Server database in Registration form Visual Studio

这是我的代码:

 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...");
            }
        }

当我尝试使用用户名和密码注册用户时-表示成功,但是数据库中唯一添加的内容是空行。 当我只单击“注册”按钮而未编写任何内容时,整个过程就会崩溃,并且会出现此错误:

违反主键约束'PK_ Login _536C85E5BD4FE4C6'。 无法在对象“ dbo.Login”中插入重复密钥。 重复的键值为()。

问题:您仅检查null和Empty,但不检查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...");
      }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM