John Ernest Guadalupe
John Ernest Guadalupe

Reputation: 6619

Why Am I getting this error in my SELECT statement in C# WinForms to MySQL Database?

I am getting this error:

Unknown column 'admin' in 'where clause'

This is my code for the Log-In button:

        mycon.Open();
        string cmdstr = "SELECT * FROM usersettingsdb WHERE user_ID = " + textBox1.Text + "";
        cmd = new MySqlCommand(cmdstr, mycon);
        dr = cmd.ExecuteReader();
        string inputpw = "";
        string dbpw = "";
        while (dr.Read())
        {
            inputpw = maskedTextBox1.Text;
            dbpw = (dr["user_pw"].ToString());
        }
        dr.Close();
        mycon.Close();

I can't quite get why I get that error since my Select statement is the same with all the other select statements I see online

Upvotes: 0

Views: 148

Answers (4)

Mr_Green
Mr_Green

Reputation: 41832

Do something like this..

 string cmdstr = string.Format("SELECT * FROM usersettingsdb " + 
                "WHERE user_ID = '{0}'", textBox1.Text.Replace("'","''"));

Replacing ' with '' because sql think ' as escape character.

But going with Parameterized queries is rocommended.

Upvotes: 1

Rab
Rab

Reputation: 35572

enclose the textbox value in single quotes

 string cmdstr = "SELECT * FROM usersettingsdb WHERE user_ID = '" + textBox1.Text + "'";

Edit:

As commented by Tigran. Use Parametarized queries instead just concatenating values from the controls

Upvotes: 7

CodeCaster
CodeCaster

Reputation: 151588

I can't quite get why I get that error

Then start debugging. Put a breakpoint on the cmd = line and inspect cmdstr's contents. You'll see the query is:

SELECT * FROM usersettingsdb WHERE user_ID = admin

Then you'll see you need to put quotes around the username. Now go read about SQL injection, parametrized queries and DAL's.

Upvotes: 3

Jon Taylor
Jon Taylor

Reputation: 7905

You need an extra set of " " in your where clause surrounding the textbox1.Text otherwise you are not passing it a string.

string cmdstr = "SELECT * FROM usersettingsdb WHERE user_ID = \"" + textBox1.Text + "\"";

Upvotes: 1

Related Questions