我目前正在尝试这样做,当您在我的网站上创建新用户时,如果名称已经存在,则应该在数据库表brugere
中检查,如果已存在,则不应该检查创建一个新用户。
但我无法让它发挥作用......
bool exists = false;
// create a command to check if the username exists
using (SqlCommand cmd1 = new SqlCommand())
cmd.CommandText = "select count(*) from brugere where bruger_navn = @bruger_navn";
{
cmd.Parameters.AddWithValue("bruger_navn", txtUsername.Text);
exists = (int)cmd.ExecuteScalar() > 0;
}
// if exists, show a message error
if (exists)
Label1. Text = "This username has been using by another user.";
else
{
// does not exists, so, persist the user
using (SqlCommand cmd2 = new SqlCommand())
cmd2.CommandText = @"INSERT INTO brugere (bruger_navn, Bruger_pass) VALUES (@bruger_navn, @bruger_pass)";
{
cmd.Parameters.AddWithValue("bruger_navn", txtUsername.Text);
cmd.Parameters.AddWithValue("bruger_pass", txtPassword.Text);
cmd.ExecuteNonQuery();
}
}
conn.Close();
答案 0 :(得分:5)
首先,您在参数名称
之前缺少@
cmd.Parameters.AddWithValue("@bruger_navn", txtUsername.Text);
....
cmd.Parameters.AddWithValue("@bruger_navn", txtUsername.Text);
cmd.Parameters.AddWithValue("@bruger_pass", txtPassword.Text);
此外,您需要为Connection
SqlCommand
属性
using (SqlCommand cmd1 = new SqlCommand())
{
cmd1.Connection = conn;
或
using (SqlCommand cmd1 = conn.CreateCommand())
{
此外,你有一些大括号和变量名称的混乱,因为我认为代码应该类似于
bool exists = false;
// create a command to check if the username exists
using (SqlCommand cmd1 = conn.CreateCommand())
{
cmd1.CommandText = "select count(*) from brugere where bruger_navn = @bruger_navn";
cmd1.Parameters.AddWithValue("bruger_navn", txtUsername.Text);
exists = (int)cmd1.ExecuteScalar() > 0;
}
// if exists, show a message error
if (exists)
Label1. Text = "This username has been using by another user.";
else
{
// does not exists, so, persist the user
using (SqlCommand cmd2 = conn.CreateCommand())
{
cmd2.CommandText = @"INSERT INTO brugere (bruger_navn, Bruger_pass) VALUES (@bruger_navn, @bruger_pass)";
cmd2.Parameters.AddWithValue("bruger_navn", txtUsername.Text);
cmd2.Parameters.AddWithValue("bruger_pass", txtPassword.Text);
cmd2.ExecuteNonQuery();
}
}
conn.Close();