我不断收到错误:
在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();
与您的代码有关的几件事...
查询中的参数名称与您使用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中。