C# 实现 MySQL 模糊查询 - 代码示例
以下是使用 C# 实现模糊查询 MySQL 表中的值的示例代码:
using MySql.Data.MySqlClient;
using System;
using System.Data;
class Program
{
static void Main()
{
string connectionString = "server=localhost;database=database_name;uid=username;password=password";
string searchQuery = "search_term";
using (MySqlConnection connection = new MySqlConnection(connectionString))
{
connection.Open();
string sqlQuery = "SELECT * FROM table_name WHERE column_name LIKE @searchTerm";
MySqlCommand command = new MySqlCommand(sqlQuery, connection);
command.Parameters.AddWithValue("@searchTerm", "%" + searchQuery + "%");
using (MySqlDataAdapter adapter = new MySqlDataAdapter(command))
{
DataTable dataTable = new DataTable();
adapter.Fill(dataTable);
foreach (DataRow row in dataTable.Rows)
{
Console.WriteLine(row["column_name"]);
}
}
}
}
}
在上面的代码中,你需要替换以下内容:
database_name:你的 MySQL 数据库名称username:你的 MySQL 用户名password:你的 MySQL 密码table_name:要查询的表名column_name:要查询的列名search_term:要模糊查询的值
代码中使用了 MySql.Data.MySqlClient 命名空间来连接 MySQL 数据库,并使用 MySqlCommand 和 MySqlDataAdapter 执行查询操作。查询语句中使用 LIKE 关键字和 @searchTerm 参数来实现模糊查询。在查询之后,将结果打印到控制台上。
请确保你已安装 MySql.Data NuGet 包以便使用 MySQL 连接和操作库。
原文地址: https://www.cveoy.top/t/topic/jDRC 著作权归作者所有。请勿转载和采集!