C# 检查用户名是否已存在于数据库中
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/15118294/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Checking if username already exists within the databasae
提问by bandaa
i am trying to check against the database table "user" to see if the "username" exists so that the same username cannot be created again. I want this to be a validator so if the username exists the message box will show it exists.
我试图检查数据库表“用户”以查看“用户名”是否存在,以便无法再次创建相同的用户名。我希望这是一个验证器,所以如果用户名存在,消息框将显示它存在。
Please guide me through this, i have the following code so far behind the button to add and check if username exists:
请指导我完成此操作,到目前为止,我在按钮后面有以下代码来添加并检查用户名是否存在:
private void btnSignupNew_Click(object sender, EventArgs e)
{
if (txtUsername.Text == "")
{
errorUsername.SetError(txtUsername, "Enter A Username");
}
else if (txtPassword.Text == "")
{
errorPassword.SetError(txtPassword, "Enter A Valid Password");
}
//so if there isnt no error in the fields itll go on and add the data in to the database.
else{
//instance of sqlConnection
SqlConnection con = new SqlConnection("Data Source=etc");
//instance of sqlCommand
SqlCommand cmd = new SqlCommand("INSERT INTO [User] values ('" + txtForename.Text + "', '" + txtSurname.Text + "', '" + txtUsername.Text + "', '" + txtPassword.Text + "' )", con);
con.Open();
cmd.ExecuteNonQuery();
//query executed correcty or not
con.Close();
采纳答案by Felipe Oriani
As a good pratice, try to keep your persistence using Parameters
to avoid SQL Injection.
作为一个好的实践,尽量保持你的持久性,Parameters
以避免 SQL 注入。
Try something liek this:
尝试这样的事情:
private void btnSignupNew_Click(object sender, EventArgs e)
{
if (txtUsername.Text == "")
{
errorUsername.SetError(txtUsername, "Enter A Username");
}
else if (txtPassword.Text == "")
{
errorPassword.SetError(txtPassword, "Enter A Valid Password");
}
else
{
using (SqlConnection con = new SqlConnection("Data Source=etc"))
{
con.Open();
bool exists = false;
// create a command to check if the username exists
using (SqlCommand cmd = new SqlCommand("select count(*) from [User] where UserName = @UserName", con))
{
cmd.Parameters.AddWithValue("UserName", txtUsername.Text);
exists = (int)cmd.ExecuteScalar() > 0;
}
// if exists, show a message error
if (exists)
errorPassword.SetError(txtUsername, "This username has been using by another user.");
else
{
// does not exists, so, persist the user
using (SqlCommand cmd = new SqlCommand("INSERT INTO [User] values (@Forname, @Surname, @Username, @Password)", con))
{
cmd.Parameters.AddWithValue("Forname", txtForname.Text);
cmd.Parameters.AddWithValue("Surname", txtSurname.Text);
cmd.Parameters.AddWithValue("UserName", txtUsername.Text);
cmd.Parameters.AddWithValue("Password", txtPassword.Text);
cmd.ExecuteNonQuery();
}
}
con.Close();
}
}
}