1

次のSQLクエリを使用してデータベースを検索しています。

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

「m」を入力して「Microsoft」を検索すると Microsoft が検索されますが、「o」を入力すると Microsoft が検索されません。

その特定の単語を含むすべてを見つけるように SQL を変更するにはどうすればよいですか?

4

2 に答える 2

0

文字を検索するときに文字列Microsoftが検索されない理由oは、条件が開始文字に基づいてフィルター処理されるためです。

この条件、

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

character で始まるすべての文字列を教えてoください。containsその文字列を検索したい場合はo、 で囲みます%%。例、

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

補足として、回避する値をパラメーター化する必要がありますSQL Injection

次のコード スニペットを試してください。

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ブロックを使用して例外を適切に処理する
于 2013-07-02T02:42:04.903 に答える
0
string sql = "SELECT [identifier] FROM [information] WHERE INSTR([identifier]," + identifier +") != 0 ";

アクセス関数 INSTR()

于 2013-07-02T02:53:20.183 に答える