Question

So I am trying to fetch a value from the database, selecting the row using WHERE INT.

conn = new MySqlConnection(DBdetails.connStr);
conn.Open();
query = "SELECT * FROM tables WHERE table=@tafel";
MySqlCommand cmd = new MySqlCommand(query, conn);
cmd.Parameters.AddWithValue("@tafel", tafel);
cmd.ExecuteNonQuery();

However it wont pass 'cmd.ExecuteNonQuery()', it throws a error saying the syntax isnt right like: "near table=1", "near table=2"

I tried fetching a other one in the same table that is a var char and it worked perfectly.

Don't really see what I am doing wrong. The 'table' column is a int and 'tafel' is a int to.

Thanks!

Was it helpful?

Solution

Put your field name table in backticks (table is a reserved word in MySQL) :

 query = "SELECT * FROM `tables` WHERE `table` = @tafel";

OTHER TIPS

As others said, table is a reserved word in MySQL. You need to use quote with it like

query = "SELECT * FROM tables WHERE `table` = @tafel";

However, the best solution is to change the name to a nonreserved word.

Also use using statement to dispose your MySqlConnection and MySqlCommand like;

using(MySqlConnection conn = new MySqlConnection(DBdetails.connStr))
using(MySqlCommand cmd = conn.CreateCommand())
{
    cmd.CommandText = "SELECT * FROM tables WHERE `table` = @tafel";
    cmd.Parameters.AddWithValue("@tafel", tafel);
    conn.Open();
    cmd.ExecuteNonQuery();
}

By the way, I don't understand why you use ExecuteNonQuery with SELECT statement. It just executes your query. It doesn't even return any value.

If you want to get the result of your query, you can use ExecuteReader method which returns SqlDataReader as your result rows.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top