【问题标题】:How to execute query SQL with LIKE when i have spaces in the string当字符串中有空格时如何使用 LIKE 执行查询 SQL
【发布时间】:2016-10-19 13:20:34
【问题描述】:

我使用 C# 中的应用程序在 Microsoft Access 2007 中创建了一个包含公司库存产品的数据库。我有一个表格可以在数据库中通过引用搜索产品,但我无法获得查询结果。问题是参考产品的列在参考名称中有各种空格:

Column product reference in the database

这是我必须执行此查询的代码:

 private void Ref_btn_Click(object sender, EventArgs e)
    {
        string connStr = (@"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=Stock.accdb");
        string query = "Select * from product where product_ref like '%' + textBox_ref.Text + '%'";

        using (OleDbConnection conn = new OleDbConnection(connStr))
        {
            using (OleDbDataAdapter adapter = new OleDbDataAdapter(query, conn))
            {
                DataSet ds = new DataSet();
                adapter.Fill(ds);
                dataGrid_stock.DataSource = ds.Tables[0];
            }



        }
    }

我想在文本框中引入例如:“VDS”或“NT”,查询分别返回“VDS 15P M X”和“NIP FIN NT LL”。

提前致谢,

【问题讨论】:

  • 你真的是说我想输入文本框"VDS" or "NT" 并且你都回来了吗?基本上,您正在尝试解析文本以获取操作顺序和“和/或”?
  • 不,不是机器人。例如,如果我输入 VDS,则查询应返回完整的参考名称。其他参考文献也是如此。但一次只有一个
  • 谢谢它的作品 AsheraH。以及如何改进我的代码以防止 SQL 注入?

标签: c# sql ms-access


【解决方案1】:

您的查询对我来说看起来不错,我只会在 textBox_ref.Text 的末尾添加一个 .Trim() 以防止在搜索词和 % 符号之间出现空格。

【讨论】:

    【解决方案2】:

    您的查询包含“错误”引号。试试这个:

    string query = "Select * from product where product_ref like '%" + textBox_ref.Text + "%'";
    

    【讨论】:

    • 感谢作品。以及如何改进我的代码以防止 SQL 注入?
    【解决方案3】:

    以下是安全执行 SQL 语句的正确方法:

    string connectionString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=Stock.accdb";
    using (SqlConnection connection = new SqlConnection(connectionString))
    {
        connection.Open();
        using (SqlCommand command = new SqlCommand(
        "SELECT * FROM product WHERE product_ref LIKE '%@value%'", connection))
        {
            command.Parameters.Add(new SqlParameter("value", textBox_ref.Text.Trim()));
            SqlDataReader reader = command.ExecuteReader();
            while (reader.Read())
            {
                // Do whatever you want to do with the queried data
            }
        }
    }
    

    此 sn-p 非常适合防止 SQL 注入。它使用所谓的参数化查询来避免安全问题。此外,它会在代码自行执行后关闭您的数据库连接。 string.Trim() 删除前导或标题空格。这可以防止意外错误。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2019-04-27
      • 1970-01-01
      • 1970-01-01
      • 2013-12-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多