Check if element exist and if not then update database c#

时间:2018-04-18 18:02:03

标签: c# sql asp.net database insert

As you can see below, I am trying to check first if username of new user already exists. If not, then to insert in database. My error is

System.Data.SqlClient.SqlException: 'Must declare the scalar variable "@username".

I am thinking about taking off the second

cmdSignUp.Parameters.Add(new SqlParameter("username", username)); 

where my //comments are.

But it's not fixed.

I think it's all because I demand the input inside a using above the Insert using.

Console.WriteLine("Select Username");
string username = Console.ReadLine();

using (SqlCommand cmdSignUp = new SqlCommand("Select Count(*) from Users where Username = @username", conn))
{
    cmdSignUp.Parameters.Add(new SqlParameter("username", username));
    int UserExists = (int)cmdSignUp.ExecuteScalar();

    if (UserExists > 0)
    {                                
        Console.WriteLine("Username already exists. Please sign up again");
        Console.ReadKey();
        Console.Clear();
    }
    else
    {
        Console.WriteLine("Enter a password 6-8 characters");
        string password = Console.ReadLine();

        using (SqlCommand cmdPass = new SqlCommand("Insert Users(Username, Password) Values(@username, @password)", conn))
        {
            // maybe the error is here? If I delete it I am getting 
            // System.Data.SqlClient.SqlException: 
            // 'Must declare the scalar variable "@username"
            cmdSignUp.Parameters.Add(new SqlParameter("username", username));                 
            cmdSignUp.Parameters.Add(new SqlParameter("password", password));

            int rows = cmdPass.ExecuteNonQuery();

            Console.WriteLine($"{rows} new user has been created. Press a key to go back to Main Menu and LogIn");
            Console.ReadKey();
        }
    }
}

1 个答案:

答案 0 :(得分:1)

It seems like it an issue with your syntax I would replace the following lines with @username and @password

cmdSignUp.Parameters.Add(new SqlParameter("@username", username));
cmdPass.Parameters.Add(new SqlParameter("@username", username))
cmdPass.Parameters.Add(new SqlParameter("@password", password));

Also, you're using the wrong reference in the else block you should be using cmPass instead of cmdSignUp