1

I've seen this question asked a couple times but I couldn't find a good answer. I've been stuck for hours on this.

Basically I have usernames saved in a database and when a new user registers I want to check if his username is available - and if it is available add him to the database. And they register through a textbox called FName. The table is called Users.

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());
}

How can I fix this code?

4

2 回答 2

7
"SELECT FName FROM Users WHERE FName = @paramUsername"

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

cmd.Parameters.Add("paramUsername", System.Data.SqlDbType.VarChar);
cmd.Parameters["paramUsername"].Value = "Theusernameyouarelookingfor";
于 2013-06-05T18:49:14.027 回答
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();

注意事项:

  • 使用参数,避免连接字符串,因为它是一个安全漏洞
  • AlwaysCloseDispose你的 ADO 对象
于 2013-06-05T18:54:24.963 回答