I'm trying to retrieve some data from a SQLite database formatted like this:
TABLE
Customers
COLUMNS
id | firstName | lastName | address | phone | email | notes
I have several TextBoxes and a DataGridView to display the data from the customers. What I'm trying to do is to retrieve and display in the DataGridView any row that matches the content of any TextBox. The code is as follows but I can't figure what I'm doing wrong with my SQL statement:
public static DataTable RecoverCustomer(Customer customer)
{
var connection = new SQLiteConnection("Data Source = prova.sqlite; Version=3;");
var command = connection.CreateCommand();
command.CommandText = "SELECT * FROM customers WHERE firstName = @firstName OR lastName = @lastName OR address = @address OR phone = @phone OR email = @email OR notes = @notes";
command.Parameters.AddWithValue("@firstName", customer.FirstName);
command.Parameters.AddWithValue("@lastName", customer.LastName);
command.Parameters.AddWithValue("@address", customer.Address);
command.Parameters.AddWithValue("@phone", customer.Phone);
command.Parameters.AddWithValue("@email", customer.Email);
command.Parameters.AddWithValue("@notes", customer.Notes);
var dataAdapter = new SQLiteDataAdapter();
var dataTable = new DataTable();
connection.Open();
dataAdapter.SelectCommand = command;
dataAdapter.Fill(dataTable);
connection.Close();
return dataTable;
}
My issue is this code returns several more rows than it should. Could it be because when adding a new customer I don't check if there's any empty field thus returning those rows when I search for a customer using this code? If yes, how can I mitigate it? This is the code I use to add a new customer to the table:
public static void CreateCustomer(Customer customer)
{
var connection = new SQLiteConnection("Data Source = prova.sqlite; Version=3;");
var command = connection.CreateCommand();
command.CommandText = "INSERT INTO customers (firstName, lastName, address, phone, email, notes) VALUES (@firstName, @lastName, @address, @phone, @email, @notes)";
command.Parameters.AddWithValue("@firstName", customer.FirstName);
command.Parameters.AddWithValue("@lastName", customer.LastName);
command.Parameters.AddWithValue("@address", customer.Address);
command.Parameters.AddWithValue("@phone", customer.Phone);
command.Parameters.AddWithValue("@email", customer.Email);
command.Parameters.AddWithValue("@notes", customer.Notes);
connection.Open();
command.ExecuteNonQuery();
connection.Close();
}
EDIT
Thanks to @Haldo I corrected my SQL statement that was matching empty spaces and it works. The correct statement is:
SELECT * FROM customers WHERE (IFNULL(@firstName, '') <> '' AND firstName = @firstName) OR (IFNULL(@lastName, '') <> '' AND lastName = @lastName) OR (IFNULL(@address, '') <> '' AND address = @address) OR (IFNULL(@phone, '') <> '' AND phone = @phone) OR (IFNULL(@email, '') <> '' AND email = @email) OR (IFNULL(@notes, '') <> '' AND notes = @notes)