【发布时间】:2020-07-20 01:03:53
【问题描述】:
有没有大师可以帮助我解决这个问题?我一直在 C# 中抛出这个异常,但我能看到的一切似乎都是正确的。这是代码
public bool Insert(loginBLL u)
{
bool isSuccess = false;
SqlConnection conn = new SqlConnection(myconnstrng);
try
{
String sql = "INSERT INTO customers (firstname, lastname, phone, email, address, city, state, zipcode, password, username) VALUES (@firstname, @lastname, @phone, @email, @address, @city, @state, @zipcode, @password, @username)";
SqlCommand cmd = new SqlCommand(sql, conn);
cmd.Parameters.AddWithValue("@firstname", u.firstname);
cmd.Parameters.AddWithValue("@lastname", u.lastname);
cmd.Parameters.AddWithValue("@phone", u.phone);
cmd.Parameters.AddWithValue("@email", u.email);
cmd.Parameters.AddWithValue("@address", u.address);
cmd.Parameters.AddWithValue("@city", u.city);
cmd.Parameters.AddWithValue("@state", u.state);
cmd.Parameters.AddWithValue("@zipcode", u.zipcode);
cmd.Parameters.AddWithValue("@password", u.password);
cmd.Parameters.AddWithValue("@username", u.username);
conn.Open();
int rows = cmd.ExecuteNonQuery();
【问题讨论】:
-
我建议避免使用
AddWithValue(),而是添加具有显式类型的参数。 -
@GordonLinoff 所以改用 cmd.Parameters.Add("@firstname", SqlDbType,varchar);
-
还有空值?
.AddWithValue("xxx", u.xxx ?? DBNull.Value); -
检查所有参数,您将 null 传递给不可为空的列,我建议使用 parameters.add
-
u.email是null(检查重复项)。