如何返回与MySQL相同或相似的任何值
本文关键字:相似 任何值 MySQL 何返回 返回 | 更新日期: 2023-09-27 18:22:07
我想在搜索txtbox中键入一个值,而银行的值类似或相等。实例
输入:G.
返回:所有带有G.的名称
如果打字的人去写乔瓦尼。只有乔瓦尼会回来。
我的代码,但它只是返回相同的
[...]"select * from users where name = " + txt_name.Text, conn);
尝试:
"SELECT * FROM users WHERE name LIKE '" + txt_name.Text +"%'"
顺便说一句,使用Parameters
是因为您的代码容易受到Sql注入的影响,比如:(我在这里使用Sql,所以只需将其更改为mySql连接、适配器等)
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);
}
}
为此尝试LIKE
运算符:
SELECT * FROM users WHERE name LIKE 'G%'
使用类似的通配符搜索
如果你想让所有的名字都有你的文字使用:
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]%'
SELECT names FROM table WHERE name LIKE '[your text]%'