如何检查数据库中是否已存在用户名

时间:2013-06-05 18:46:49

标签: c# database

我已经看过几次这个问题,但我找不到一个好的答案。我已经被困了好几个小时了。

基本上我将用户名保存在数据库中,当新用户注册时我想检查他的用户名是否可用 - 如果可用,则将他添加到数据库中。他们通过名为FName的文本框注册。该表称为用户。

SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString);

SqlCommand cmd = new SqlCommand("SELECT FName FROM Users WHERE FName =  ????? usernames????? ", con);

con.Open();
SqlDataReader reader = cmd.ExecuteReader();
while (reader.Read()) 
{
     Console.WriteLine(reader["text"].ToString());
}

如何修复此代码?

2 个答案:

答案 0 :(得分:7)

"SELECT FName FROM Users WHERE FName = @paramUsername"

然后将参数插入到cmd中,如下所示:

cmd.Parameters.Add("paramUsername", System.Data.SqlDbType.VarChar);
cmd.Parameters["paramUsername"].Value = "Theusernameyouarelookingfor";

答案 1 :(得分:1)

检查出来:

SqlConnection connection = new SqlConnection(ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString);

string validationQuery = "SELECT * FROM Users WHERE FName = @name";
SqlCommand validationCommand = new SqlCommand(validationQuery, connection);
validationCommand.Parameters.Add("@name", SqlDbType.VarChar).Value = loginUserSelected;

connection.Open();

SqlDataReader validationReader = validationCommand.ExecuteReader(CommandBehavior.CloseConnection);

if (!validationReader.Read())
{
    string insertQuery = "INSERT INTO Users (FName) VALUES (@name)";
    SqlCommand insertCommand = new SqlCommand(insertQuery, connection);
    insertCommand.Parameters.Add("@name", SqlDbType.VarChar).Value = loginUserSelected;

    connection.Open();

    insertCommand.ExecuteNonQuery();

    insertCommand.Dispose();

    connection.Close();
}
else
{
    //Uh oh, username already taken
}

validationReader.Close();

validationCommand.Dispose();

注意事项:

  • 使用参数,避免连接字符串,因为它是一个安全漏洞
  • 您的ADO对象始终为CloseDispose