如何解决未处理的Sqlexception

问题描述 投票:-2回答:1

我不断收到错误:

在System.Data.dll中发生了'System.Data.SqlClient.SqlException类型的未处理的异常

代码:

cmd = new SqlCommand("INSERT INTO UserRegister(LastName, FirstName, M.I, Username, Password, Email, Address, ContactNumber, Gender, BloodType)  
                      VALUES (@txtLName, @txtFName, @txtMI, @txtRegUsername, @txtRegPassword, @txtEmail, @txtHomeAddress, @txtContactno, @cmbGender, @cmbBloodtype)", sql);

cmd.Parameters.AddWithValue("@LastName", txtLName.Text);
cmd.Parameters.AddWithValue("@FirstName", txtFName.Text);
cmd.Parameters.AddWithValue("@M.I", txtMI.Text);
cmd.Parameters.AddWithValue("@Username", txtRegusername.Text);
cmd.Parameters.AddWithValue("@Password", txtRegpassword.Text);
cmd.Parameters.AddWithValue("@Email", txtEmail.Text);
cmd.Parameters.AddWithValue("@Address", txtHomeaddress.Text);
cmd.Parameters.AddWithValue("@ContactNumber", txtContactno.Text);
cmd.Parameters.AddWithValue("@Gender", cmbGender.Text);
cmd.Parameters.AddWithValue("@BloodType", cmbBloodtype.Text);

cmd.ExecuteNonQuery();
sql.Dispose();
c# sql-server windows-forms-designer
1个回答
0
投票

与您的代码有关的几件事...

查询中的参数名称与您使用AddWithValue添加的参数不匹配,因此这就是查询失败的原因。他们需要匹配,例如:

var cmd = new SqlCommand("INSERT INTO UserRegister(LastName, FirstName, M.I, Username, Password, Email, Address, ContactNumber, Gender, BloodType) VALUES(@txtLName, @txtFName, @txtMI, @txtRegUsername, @txtRegPassword, @txtEmail, @txtHomeAddress, @txtContactno, @cmbGender, @cmbBloodtype)", sql);
            cmd.Parameters.AddWithValue("@LastName", txtLName.Text);
            cmd.Parameters.AddWithValue("@txtFName", txtFName.Text);
            cmd.Parameters.AddWithValue("@txtMI", txtMI.Text);
            cmd.Parameters.AddWithValue("@txtRegUsername", txtRegusername.Text);
            cmd.Parameters.AddWithValue("@txtRegPassword", txtRegpassword.Text);
            cmd.Parameters.AddWithValue("@txtEmail", txtEmail.Text);
            cmd.Parameters.AddWithValue("@txtHomeAddress", txtHomeaddress.Text);
            cmd.Parameters.AddWithValue("@txtContactno", txtContactno.Text);
            cmd.Parameters.AddWithValue("@cmbGender", cmbGender.Text);
            cmd.Parameters.AddWithValue("@cmbBloodtype", cmbBloodtype.Text);
            cmd.ExecuteNonQuery();

您还应该阅读Can we stop using AddWithValue() already?

而不是调用sql.Dispose();,而是将连接对象放在using statement中。

© www.soinside.com 2019 - 2024. All rights reserved.