C# SQLite getting an SQL logic error when trying to SELECT * FROM

Viewed 45

I am trying to select data from a SQLite database using a variable from a textbox to display it in a dataGridView. This is the line:

SQLiteCommand sql = new SQLiteCommand("SELECT * FROM Customers WHERE name like ''" + textBox1.Text, m_dbConnection);
SQLiteDataReader read = sql.ExecuteReader();

When I attempt to search using the letter 't' the following error is thrown.

System.Data.SQLite.SQLiteException: 'SQL logic error near "t": syntax error'.

'Customer' is the table, 'name' is the column.

Seems like it is getting the value from the textbox, but I am missing something.

Thanks.

2 Answers

Use a parameterized query SqlCommand Parameters

var sql = new SqlCommand(
    "SELECT * FROM Customers WHERE name like @Name",
    m_dbConnection
);
var param = new SqlParameter();
param.ParameterName = "@Name";
param.Value = textBox1.Text;
cmd.Parameters.Add(param);

I hope this fixes it. I can't comment but i want to help you out. First you said that the Tables name is "Customer" but you wrote "Customers" Second is your Syntax wrong. It should be like this:

SQLiteCommand sql = new SQLiteCommand("SELECT * FROM Customer WHERE name = '" + textBox1.Text + "'", m_dbConnection);
SQLiteDataReader read = sql.ExecuteReader();

I hope i could help!

Edit: Made myself a Syntax Error xD but fixed it now

Related