【发布时间】:2018-12-05 10:48:39
【问题描述】:
我正在尝试从格式如下的 SQLite 数据库中检索一些数据:
表格
Customers
列
id | firstName | lastName | address | phone | email | notes
我有几个 TextBox 和一个 DataGridView 来显示来自客户的数据。我要做的是在 DataGridView 中检索并显示与任何 TextBox 的内容匹配的任何行。代码如下,但我不知道我的 SQL 语句做错了什么:
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;
}
我的问题是此代码返回的行数超出了应有的行数。可能是因为在添加新客户时我不检查是否有任何空字段因此在我使用此代码搜索客户时返回这些行? 如果是,我该如何缓解?这是我用来向表中添加新客户的代码:
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();
}
编辑
感谢@Haldo,我更正了与空格匹配的 SQL 语句,它可以正常工作。正确的说法是:
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)
【问题讨论】:
-
是什么让你觉得你做错了什么?
-
运行代码时是否报错?还是返回错误值?
-
@Caius Jard 我的错,用更具体的要求编辑了我的问题。
-
它返回了哪些不应该返回的行? (这一系列问题正在发展你解决问题的思维过程,以及改进你向那些不知道你的系统如何运作的人提问的方式——本质上它是在教你钓鱼而不是给你一条鱼)
-
@Haldo 谢谢!尽管使用 SQLite 似乎语法是不同的
IFNULL(x, y)而不是ISNULL(x, y)这似乎是一种魅力!再次将其作为 anwser 发布,我会相应地标记它。