Saturn
Saturn

Reputation: 18139

MySql is returning column name, not value

myCommand.CommandText = "SELECT 'USED' FROM `KEYS` WHERE `KEYS`.`KEY` = '" + TextBox1.Text + "'"

Dim myReader As MySqlDataReader
            myReader = myCommand.ExecuteReader
            While (myReader.Read())
                MessageBox.Show(myReader.GetString(0))
            End While

The returning string is "USED". But that is wrong: it should be returning integer 0 instead. Why is that?

Edit: I changed the MessageBox line to MessageBox.Show(myReader.GetInt16(0)) but now it sends me an error telling me that the input string is not in the right format..

Upvotes: 1

Views: 558

Answers (5)

Lion
Lion

Reputation: 19027

Change here

"SELECT `USED` FROM `KEYS` WHERE `KEYS`.`KEY` = '" + TextBox1.Text + "'"

You need to insert backticks and not single quotes.

Upvotes: 0

Christopher Mahan
Christopher Mahan

Reputation: 7619

single quoted around the name 'USED' tell it to return the word 'USED' in an unnamed column.

Upvotes: 1

AlfredoVR
AlfredoVR

Reputation: 4287

Remove the 'USED' and write used instead.

Upvotes: 1

Icarus
Icarus

Reputation: 63956

You are using the wrong quotes; you need to use ` as so:

myCommand.CommandText = "SELECT `USED` FROM `KEYS` WHERE `KEYS`.`KEY` = '" + TextBox1.Text + "'"

Upvotes: 1

Eric
Eric

Reputation: 95093

You need backtick, not apostrophe ` not '

You're actually selecting the string "USED" rather than the column. You could just remove the apostrophes all together and say

myCommand.CommandText = "SELECT USED FROM `KEYS` WHERE `KEYS`.`KEY` = '" + TextBox1.Text + "'"

Also as a note, don't use dynamic SQL--used prepared queries:

myCommand.CommandText = "SELECT USED FROM KEYS WHERE KEYS.KEY = @Key";
myCommand.Parameters.AddWithValue("@Key", TextBox1.Text);

Otherwise you're very susceptible to SQL injection (which is a very bad thing).

Upvotes: 4

Related Questions