c# 模糊搜索MySQL MySQL只包含一个表搜索出这个表中包含搜索词的所有行并在dataGridView中展示
以下是一个在C#中使用MySQL数据库进行模糊搜索,并将结果展示在DataGridView中的示例代码:
using System;
using System.Data;
using System.Windows.Forms;
using MySql.Data.MySqlClient;
namespace FuzzySearchApp
{
public partial class Form1 : Form
{
private MySqlConnection connection;
private MySqlCommand command;
private MySqlDataAdapter adapter;
private DataTable table;
public Form1()
{
InitializeComponent();
ConnectToDatabase();
}
private void ConnectToDatabase()
{
string connectionString = "server=localhost;user=root;database=your_database_name;port=3306;password=your_password;";
connection = new MySqlConnection(connectionString);
}
private void SearchButton_Click(object sender, EventArgs e)
{
string searchKeyword = SearchTextBox.Text;
string query = $"SELECT * FROM your_table_name WHERE column_name LIKE '%{searchKeyword}%'";
try
{
command = new MySqlCommand(query, connection);
adapter = new MySqlDataAdapter(command);
table = new DataTable();
adapter.Fill(table);
dataGridView1.DataSource = table;
}
catch (Exception ex)
{
MessageBox.Show("Error: " + ex.Message);
}
}
}
}
在上面的代码中,你需要将your_database_name替换为你的数据库名称,your_table_name替换为你的表名,column_name替换为你要在其中进行模糊搜索的列名。
你需要确保已经通过NuGet包管理器安装了MySQL Connector/Net,以便在C#项目中使用MySQL数据库。
原文地址: https://www.cveoy.top/t/topic/i8xd 著作权归作者所有。请勿转载和采集!