编写代码:c# 实现:MySQL表中含有四列列名为姓名年龄手机号日期模糊查询表中的值
以下是一个使用 C# 实现模糊查询 MySQL 表的示例代码:
using System;
using MySql.Data.MySqlClient;
class Program
{
static void Main()
{
string connStr = "server=localhost;user=root;database=test;port=3306;password=your_password";
MySqlConnection conn = new MySqlConnection(connStr);
try
{
conn.Open();
Console.Write("请输入要查询的关键字: ");
string keyword = Console.ReadLine();
string query = "SELECT * FROM your_table WHERE 姓名 LIKE @keyword OR 年龄 LIKE @keyword OR 手机号 LIKE @keyword OR 日期 LIKE @keyword";
MySqlCommand cmd = new MySqlCommand(query, conn);
cmd.Parameters.AddWithValue("@keyword", "%" + keyword + "%");
MySqlDataReader rdr = cmd.ExecuteReader();
while (rdr.Read())
{
Console.WriteLine("姓名: {0}, 年龄: {1}, 手机号: {2}, 日期: {3}", rdr.GetString(0), rdr.GetInt32(1), rdr.GetString(2), rdr.GetDateTime(3));
}
rdr.Close();
}
catch (Exception ex)
{
Console.WriteLine("查询出错: " + ex.Message);
}
finally
{
conn.Close();
}
}
}
请注意替换以下部分:
server=localhost:将localhost替换为你的 MySQL 服务器地址。user=root:将root替换为你的 MySQL 用户名。database=test:将test替换为你要查询的数据库名。port=3306:将3306替换为你的 MySQL 服务器端口号。password=your_password:将your_password替换为你的 MySQL 密码。your_table:将your_table替换为你要查询的表名。
此代码将提示用户输入要查询的关键字,然后查询 MySQL 表中包含该关键字的记录,并将结果输出到控制台。
原文地址: http://www.cveoy.top/t/topic/i9Dc 著作权归作者所有。请勿转载和采集!