【发布时间】:2017-06-03 00:19:28
【问题描述】:
我正在编写一个 C# 应用程序,但我一直在搜索数据库和填充数据网格视图。但是我想将它与命令生成器一起使用。
问题是,我需要对数据库中的所有列进行搜索。我认为使用 OR 和 LIKE 语句可以做到这一点。但相反,我得到无效的语法或搜索中不存在列名。
有人知道解决办法吗?
我现在的.cs:
private void btnSearchJob_Click(object sender, EventArgs e)
{
try
{
SqlConnection con = new SqlConnection();
con.ConnectionString = (@"Data Source=(localdb)\MSSQLLocalDB;Initial Catalog=MTR_Database;Integrated Security=True");
string selectQuery = "SELECT * FROM dbo.[" + cmbJobName.Text + "] WHERE ([Job Name] LIKE " +txtSearchJob.Text+ " OR [Manufacturer] LIKE " +txtSearchJob.Text+ ")";
// DataAdapter
myDA = new SqlDataAdapter(selectQuery, con);
// SqlCommand
SqlCommand myCMD = new SqlCommand(selectQuery, con);
// DataAdapter to Command
myDA.SelectCommand = myCMD;
// Define Datatable
myDT = new DataTable();
// Command Builder (IS GOD!)
SqlCommandBuilder cb = new SqlCommandBuilder(myDA);
// Teach Command builder to be a boss!
myDA.UpdateCommand = cb.GetUpdateCommand();
myDA.InsertCommand = cb.GetInsertCommand();
myDA.DeleteCommand = cb.GetDeleteCommand();
// Fill the DataTable with DataAdapter information
myDA.Fill(myDT);
// Fill DataTable with Database Schema
myDA.FillSchema(myDT, SchemaType.Source);
// Bind The Data Table to the DataGrid
dataGridView1.DataSource = myDT;
// AutoSize Datagrid Rows and Colums to fit the Datagrid
dataGridView1.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.AllCells;
dataGridView1.AutoSizeRowsMode = DataGridViewAutoSizeRowsMode.AllCells;
}
// Catch Exception
catch (Exception ex)
{
MessageBox.Show(this, ex.Message, "SQL ERROR", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
注意:
我知道使用参数,我只是用它来看看它是否会在我稍后添加参数时起作用。
【问题讨论】:
-
Beware of little bobby tables. 很高兴知道您知道使用参数,您还应该知道您不能参数化标识符这一事实。
-
每个“工作”都有自己的表?
-
正确,每个作业都有自己的表格。我还有一个主列表,每个插入都与作业表一起放入主表中。所以我需要对每个表进行搜索,并且我将单独搜索主列表。
标签: c# sql search datagridview multiple-columns