-5

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.

  • 1
    A simple problem which can be solved using SQL Parameters. Gluing data into strings - especially user entered data - has never been the correct method in .NET – Ňɏssa Pøngjǣrdenlarp Sep 10 '22 at 23:11
  • 1
    Obviously using parameters is the best solution. An easy way to see what the problem is, is to see what query is generated (aka debugging, an essential part of any programming) – HoneyBadger Sep 10 '22 at 23:14

2 Answers2

1

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);
jitter
  • 53,475
  • 11
  • 111
  • 124
-2

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

001Sarper
  • 33
  • 2