Basix
Basix

Reputation: 3

C# MySql Unknown column in where clause

After I try to output the password in the dataGrid, from the given Username in the txt_Username textbox, I get this error message:

MySql.Data.MySqlClient.MySqlException: "Unknown column 'Test' in 'where clause'"

MySqlDataAdapter da = new MySqlDataAdapter("Select Password from tbl_anmeldedaten Where Username=" + txt_Username.Text, con);
da.SelectCommand.CommandType = CommandType.Text;
DataTable dt = new DataTable();
da.Fill(dt);
dataGridView1.DataSource = dt;

Upvotes: 0

Views: 2884

Answers (2)

Tim Biegeleisen
Tim Biegeleisen

Reputation: 520898

The exact cause of the error is that you are trying to execute the following query:

SELECT Password
FROM tbl_anmeldedaten
WHERE Username = Test;

Does it look like Test should have single quotes around it? Yes, it should, and you could add that to your raw query. But, concatenating a query like this in C# leaves open the possibility for SQL injection. A much better approach is to use prepared statements:

string sql = "SELECT Password FROM tbl_anmeldedaten WHERE Username = @val1";
MySqlCommand cmd = new MySqlCommand(sql, MySqlConn.conn);
cmd.Parameters.AddWithValue("@val1", txt_Username.Text);
cmd.Prepare();
MySqlDataReader rdr = cmd.ExecuteReader();
while (rdr.Read()) 
{
    // consume a record in the result set
}

Upvotes: 3

Daniel A. White
Daniel A. White

Reputation: 190907

You are using string concatenation which is a vector for SQL injection attacks. Perhaps the username in the text field is doing some SQL which it shouldn't be allowed to (for instance '' OR Test=1. There are plenty of resources on using parameterized queries which should remedy the problem.

Upvotes: -1

Related Questions