我在文本框中遇到错误搜索数据库。 数据库是Northwind.dbo
当我在文本框中键入一个字符时。它有这个错误 谢谢你的回答
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Data.SqlClient;
namespace Lab10_2 {
public partial class Form1 : Form
{
SqlConnection Conn;
SqlCommand Cmd;
SqlDataAdapter da;
DataSet ds;
DataTable dt;
SqlCommandBuilder CmdBld;
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
savebtn.Enabled = false;
delbtn.Enabled = false;
editbtn.Enabled = false;
String StrConn = "Data Source=POOMJIRAROJ;Initial Catalog=Northwind;Integrated Security=True;Connect Timeout=15;Encrypt=False;TrustServerCertificate=False;ApplicationIntent=ReadWrite;MultiSubnetFailover=False";
Conn = new SqlConnection(StrConn);
Conn.Open();
}
private void loadbtn_Click(object sender, EventArgs e)
{
loadbtn.Enabled = false;
editbtn.Enabled = true;
delbtn.Enabled = false;
savebtn.Enabled = false;
String StrQry = "select *From Customers";
Cmd = new SqlCommand(StrQry,Conn);
da = new SqlDataAdapter(Cmd);
ds = new DataSet();
dt = new DataTable();
da.Fill(ds, "Customers");
dt = ds.Tables["Customers"];
CmdBld = new SqlCommandBuilder(da);
dataGridView1.DataSource = dt;
dataGridView1.ReadOnly = true;
dataGridView1.SelectionMode = DataGridViewSelectionMode.FullRowSelect;
Conn.Close();
}
private void editbtn_Click(object sender, EventArgs e)
{
dataGridView1.ReadOnly = false;
loadbtn.Enabled = false;
editbtn.Enabled = true;
delbtn.Enabled = true;
savebtn.Enabled = true;
}
private void savebtn_Click(object sender, EventArgs e)
{
da.Update(dt);
dataGridView1.ReadOnly = true;
savebtn.Enabled = false;
delbtn.Enabled = false;
editbtn.Enabled = true;
}
private void delbtn_Click(object sender, EventArgs e)
{
if(MessageBox.Show("Delete This Row","Delete",MessageBoxButtons.YesNo) == DialogResult.Yes)
{
dataGridView1.Rows.RemoveAt(dataGridView1.SelectedRows[0].Index);
da.Update(dt);
}
}
private void txtSearch_TextChanged(object sender, EventArgs e)
{
SqlDataAdapter StrQry = new SqlDataAdapter("Select CustomerID, CompanyName, ContractTitle, Country From Customers Where (CompanyName ' %" +txtSearch.Text+ "% ')", Conn);
ds = new DataSet();
StrQry.Fill(ds);
dataGridView1.DataSource = ds;
}
}
}
答案 0 :(得分:1)
您缺少WHERE子句中的运算符
SqlDataAdapter StrQry = new SqlDataAdapter(@"
Select CustomerID, CompanyName, ContractTitle, Country
From Customers Where CompanyName LIKE @search", Conn);
StrQuery.SelectCommand.Parameters.Add("@search", SqlDbType.NVarWChar).Value = "%" + txtSearch.Text +"%";
运算符需要完成where子句,我使用LIKE搜索包含所键入字母的每个文本,并使用参数执行搜索
永远不要使用字符串连接来构建sql命令。您的代码可能会被一个名为Sql Injection
的简单tecnique攻击