【问题标题】:how to find a text in database using c# [duplicate]如何使用c#在数据库中查找文本[重复]
【发布时间】:2013-02-04 19:12:50
【问题描述】:

可能重复:
how to make search of a string in a data base in c#

我想详细搜索一个名字..这是搜索按钮的代码

private void button1_Click(object sender, EventArgs e)
{
    string connectionString = Tyres.Properties.Settings.Default.Database1ConnectionString;
    SqlConnection conn = new SqlConnection(connectionString);
    DataTable dt = new DataTable();
    SqlDataAdapter SDA = new SqlDataAdapter("SELECT * FROM table1 where Details like" + textBox1.Text, conn);
    SDA.Fill(dt);
    dataGridView1.DataSource = dt;
}

和我的应用程序的这个例子

我收到错误:

An unhandled exception of type 'System.Data.SqlClient.SqlException' occurred in System.Data.dll

附加信息:在预期条件的上下文中指定的非布尔类型表达式,靠近“likeelie”。

我已尝试使用此代码搜索整数(如 Quantity),它对我很有效:

private void button1_Click(object sender, EventArgs e)
{
    string connectionString = Tyres.Properties.Settings.Default.Database1ConnectionString;
    SqlConnection conn = new SqlConnection(connectionString);
    DataTable dt = new DataTable();
    SqlDataAdapter SDA = new SqlDataAdapter("SELECT * FROM table1 where Quantity like" + int.parse(textBox1.Text), conn);
    SDA.Fill(dt);
    dataGridView1.DataSource = dt;
}

所以我需要关于第一个代码的帮助

【问题讨论】:

标签: c# c#-4.0 c#-3.0 c#-2.0


【解决方案1】:

看起来您需要在 SQL 语句中添加一个空格,您只是在没有空格的情况下附加了 textBox1.Text 的值,因此 textBox.Text 的值与 like 成为一个单词。

SqlDataAdapter SDA = new SqlDataAdapter("SELECT * FROM table1 where Details like " + textBox1.Text, conn);

【讨论】:

  • 我还建议使用 SqlParameters HERE
  • 现在我遇到了另一个问题:System.Data.dll 中发生了“System.Data.SqlClient.SqlException”类型的未处理异常附加信息:列名“Audi”无效。
  • @user1951045 你应该发布另一个问题来得到它。不确定如何从您发布的内容中获得无效的列名。您通过textBox1 提供的任何内容都可能是问题的根源。动态构建的 SQL 可能很棘手,如果输入未经过过滤,它们会允许 SQL 注入攻击,因此首选存储过程。
  • 他得到了这个错误,因为他在他的 SQL 中放了一个普通的不带引号的字符串。所以他的输入就像一个列名。
猜你喜欢
  • 2020-06-22
  • 1970-01-01
  • 2010-10-01
  • 2010-09-30
  • 2019-06-14
  • 2020-01-10
  • 2018-12-12
  • 1970-01-01
  • 2016-02-26
相关资源
最近更新 更多