我有用户的 SQL Server 数据库,现在我想为这个表做简单的搜索算法。我的目标是制作可以组合搜索多个单词的算法,所以我尝试了这种策略:当按下搜索按钮时,方法首先从搜索字符串中提取单个单词,然后将它们作为参数插入到SqlCommand
CommandText
.
它适用于一个单词,但当我输入多个单词时它会卡住。这是代码示例:
private void btnSearchUsers_Click(object sender, EventArgs e)
{
command = new SqlCommand();
adapter = new SqlDataAdapter();
dataset = new DataSet();
try
{
User.connection.Open();
command.CommandText = "SELECT * FROM tbl_Users WHERE userActive = 1";
if (!String.Empty.Equals(tboxInputUsers.Text))
{
command.CommandText += " AND";
string[] words = tboxInputUsers.Text.Split(' ');
string id = "id";
foreach (string word in words)
{
id += "a";
command.CommandText += String.Format(" userUsername LIKE @{0} OR userName LIKE @{0} OR userSurname LIKE @{0}", id);
command.Parameters.AddWithValue(String.Format("@{0}", id), word);
}
}
command.Connection = User.connection;
adapter.SelectCommand = command;
adapter.Fill(dataset);
}
catch (SqlException ex)
{
MessageBox.Show(ex.Message, Application.ProductName, MessageBoxButtons.OK, MessageBoxIcon.Information);
}
finally
{
if (ConnectionState.Open.Equals(User.connection.State)) Korisnik.connection.Close();
}
DataTable table = new DataTable();
table = dataset.Tables[0];
dgvUsers.DataSource = table;
dgvUsers.Columns[0].Visible = false;
}
当我进入调试模式并输入两个单词时,command.Parameters 显示它有 2 个参数,但它仍然崩溃。任何见解有什么问题?
谢谢!
== 编辑 ==
我得到这种类型
SqlException:'userUsername' 附近的语法不正确