【问题标题】:Searching access database with keyword使用关键字搜索访问数据库
【发布时间】:2013-07-02 02:33:59
【问题描述】:

我正在使用以下 SQL 查询来搜索数据库。

string sql = "SELECT [identifier] FROM [information] WHERE [identifier] LIKE '" + identifier + "%'";

当我输入“m”搜索“Microsoft”时,它会找到 Microsoft,但如果我输入“o”,它不会找到 Microsoft。

如何更改 SQL 以便它找到包含该特定单词的所有内容?

【问题讨论】:

  • 此处注意SQL注入漏洞。

标签: c# asp.net sql search


【解决方案1】:

搜索字母o时不搜索字符串Microsoft的原因是因为你的条件是根据起始字符过滤的。

这个条件,

... WHERE [identifier] LIKE 'o%'

表示..给我所有以字符o开头的字符串。如果要搜索contains 字符o 的字符串,则应将其包装为%%。例如,

... WHERE [identifier] LIKE '%o%'

作为旁注,您应该参数化这些值以避免SQL Injection

试试这个代码 sn-p:

string connStr = "connection string here";
string content = string.Format("{0}{1}{0}", "%", identifier);
string sqlStatement = "SELECT [identifier] FROM [information] WHERE [identifier] LIKE ?";
using (SqlConnection conn = new SqlConnection(connStr))
{
    using(SqlCommand comm = new SqlCommand())
    {
        comm.Connection = conn;
        comm.CommandText = sqlStatement;
        comm.CommandType = CommandType.Text;

        comm.Parameters.AddWithValue("@content", content);

        try
        {
            conn.Open();
            // other codes
        }
        catch(SqlException e)
        {
            // do something with the exception
            // do not hide it
            // e.Message.ToString()
        }
    }
}

为了正确编码

  • 使用using 语句进行正确的对象处理
  • 使用try-catch 块正确处理异常

【讨论】:

  • 我试过了,但没有用 "SELECT [identifier] FROM [information] WHERE [identifier] LIKE '%" + identifier + "%'";
【解决方案2】:
string sql = "SELECT [identifier] FROM [information] WHERE INSTR([identifier]," + identifier +") != 0 ";

ACCESS function INSTR()

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-08-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-09-20
    • 1970-01-01
    相关资源
    最近更新 更多