【发布时间】:2023-03-27 22:21:01
【问题描述】:
我开始学习 ASP.NET。我创建了一个注册系统,当我尝试检查数据库中是否已经存在用户名或电子邮件时,它不会被检查并创建用户,即使你已经拥有它。
try
{
conn.Open();
bool exists = false;
string checkuser = "SELECT count(*) FROM accounts WHERE username='" + username.Text + "'";
SqlCommand cmd2 = new SqlCommand(checkuser, conn);
cmd2.Parameters.AddWithValue("username", username.Text);
exists = (int)cmd2.ExecuteScalar() > 0;
if (exists)
{
Response.Write("User already exists");
}
string command = "INSERT INTO accounts (username, email, password) VALUES (@username, @email, @password)";
SqlCommand cmd = new SqlCommand(command, conn);
cmd.Parameters.AddWithValue("@username", username.Text);
cmd.Parameters.AddWithValue("@email", email.Text);
cmd.Parameters.AddWithValue("@password", password.Text);
cmd.ExecuteNonQuery();
}
catch(Exception)
{
label_msg.Visible = true;
label_msg.Text = "Something went wrong....";
throw;
}
finally
{
Response.Redirect("/layout.aspx");
conn.Close();
}
谢谢!
【问题讨论】:
-
为什么使用 cmd2.Parameters.AddWithValue("username", username.Text);因为你在 cmd2 中没有 @username 参数
标签: c# html css asp.net visual-studio