mysql遍历查询+C#_c# 遍历 Mysql 所有表所有列,查找目标数据

该博客介绍了如何使用C#语言连接到MySQL数据库,遍历所有表及其列,并通过`information_schema.columns`获取表结构。然后,它演示了如何在每个表的每个列中搜索特定字符串,输出包含该字符串的表名和列名。
摘要由CSDN通过智能技术生成

using MySql.Data.MySqlClient;

using System;

using System.Collections.Generic;

using System.Linq;

using System.Text;

using System.Threading.Tasks;

namespace ConsoleApp1

{

class Program

{

static void Main(string[] args)

{

List list = GetTableList();

Query(list, "1111aaaa");

Console.WriteLine("over");

Console.ReadLine();

}

static List GetTableList()

{

using (MySqlConnection conn = GetConnection())

{

Dictionary dic = new Dictionary();

MySqlCommand cmd = conn.CreateCommand();

cmd.CommandText = "select table_name, column_name from information_schema.columns where table_schema = 'mydb';";

using (MySqlDataReader reader = cmd.ExecuteReader())

{

while (reader.Read())

{

string table = reader.GetString("table_name");

string column = reader.GetString("column_name");

if (dic.ContainsKey(table))

{

dic[table].ColumnList.Add(column);

}

else

{

MyTable t = new MyTable();

t.Table = table;

t.ColumnList.Add(column);

dic.Add(t.Table, t);

}

}

}

return dic.Values.ToList();

}

}

static void Query(List list, string str)

{

using (MySqlConnection conn = GetConnection())

{

MySqlCommand cmd = conn.CreateCommand();

foreach (MyTable table in list)

{

foreach (string column in table.ColumnList)

{

cmd.CommandText = string.Format("select count(*) from {0} where `{1}` like '%{2}%'", table.Table, column, str);

object obj = cmd.ExecuteScalar();

if (Convert.ToInt32(obj) > 0)

{

Console.WriteLine(string.Format("TableName: {0}, ColumnName: {1}", table.Table, column));

}

}

}

}

}

static MySqlConnection GetConnection()

{

MySqlConnection conn = new MySqlConnection("server=localhost;port=3306;user id=userid;password=pass;database=mydb;pooling=true;ConnectionTimeout=1800");

conn.Open();

return conn;

}

}

public class MyTable

{

public string Table { get; set; }

public List ColumnList { get; set; } = new List();

}

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值