使用 C# 代码搜索 MySQL 数据库中单个表的全部列,找出包含指定关键词的所有行,并展示在 DataGridView 控件中。

以下是一个示例代码,可以搜索 MySQL 数据库中的一个表,找出所有包含搜索词的行,并在 dataGridView 中展示:

using System;
using System.Data;
using System.Windows.Forms;
using MySql.Data.MySqlClient;

namespace SearchMySQLTable
{
    public partial class Form1 : Form
    {
        private MySqlConnection connection;
        private string server;
        private string database;
        private string uid;
        private string password;

        public Form1()
        {
            InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            server = "localhost"; // MySQL服务器地址
            database = "your_database"; // 数据库名称
            uid = "your_username"; // 用户名
            password = "your_password"; // 密码

            string connectionString = "SERVER=" + server + ";" + "DATABASE=" +
                database + ";" + "UID=" + uid + ";" + "PASSWORD=" + password + ";";

            connection = new MySqlConnection(connectionString);
        }

        private void btnSearch_Click(object sender, EventArgs e)
        {
            string searchKeyword = txtSearch.Text;

            try
            {
                connection.Open();

                string query = "SELECT * FROM your_table WHERE column_name LIKE '%" + searchKeyword + "%'";
                MySqlCommand cmd = new MySqlCommand(query, connection);

                MySqlDataAdapter adapter = new MySqlDataAdapter(cmd);
                DataTable dataTable = new DataTable();
                adapter.Fill(dataTable);

                dataGridView.DataSource = dataTable;
            }
            catch (Exception ex)
            {
                MessageBox.Show("Error: " + ex.Message);
            }
            finally
            {
                connection.Close();
            }
        }
    }
}

在这个示例中,你需要将your_database替换为你的数据库名称,your_usernameyour_password替换为你的MySQL用户名和密码,your_table替换为你要搜索的表名称,column_name替换为你要在其中搜索的列名称。

C# MySQL 搜索表所有列并展示结果 - DataGridView 示例

原文地址: https://www.cveoy.top/t/topic/lJk8 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录