如何返回任何等于或类似MySQL的值

时间:2013-07-13 05:07:01

标签: c# mysql database

我希望在搜索txtbox中输入一个值,并且银行类似或相等。实施例。

输入:G。

返回:所有带有G。

的名称

如果打字的人甚至会写Giovanni。只有Giovanni将被退回。

我的代码,但它只返回相同的

[...]"select * from users where name = " + txt_name.Text, conn);

4 个答案:

答案 0 :(得分:1)

尝试:

"SELECT * FROM users WHERE name LIKE '" + txt_name.Text +"%'"

顺便使用Parameters,因为您的代码容易受到 Sql Injection 的影响:(我在这里使用Sql,所以只需将其更改为mySql Connection,Adapter等)< / p>

        using (SqlConnection connection = new SqlConnection(connString))
        {
          string sql = "SELECT * FROM users WHERE name LIKE @NameSearch";
            try
            {
                connection.Open();
                using (SqlDataAdapter da = new SqlDataAdapter(sql, connection))
                {

                    using (SqlCommand cmd = new SqlCommand())
                    {
                        da.SelectCommand.Parameters.AddWithValue("@NameSearch", txt_Name.Text+"%");

                            DataTable dt = new DataTable();
                            da.Fill(dt);                                                                   
                    }
                }

            }
            catch (Exception ex)
            {
              MessageBox.Show(ex.Message);
            }

        }

答案 1 :(得分:0)

使用像

这样的野性字符搜索

如果您希望所有姓名都在您的文本中使用:

Select names from table where name like '%[your text]%'

如果您希望所有以文字开头的名称使用:

Select names from table where name like '[your text]%'

如果您希望所有以文字结尾的名称使用:

Select names from table where name like '%[your text]%'

答案 2 :(得分:0)

尝试使用LIKE运算符:

SELECT * FROM users WHERE name LIKE 'G%'

答案 3 :(得分:0)

SELECT names FROM table WHERE name LIKE '[your text]%'