pip install pymysql
import pymysql
# 数据库连接配置
db_config = {
"host": "127.0.0.1", #数据库地址
"user": "root", #数据库用户名
"password": "root", #数据库密码
"db": "saas", #数据库
"charset": "utf8mb4"
}
# 搜索关键词
search_keyword = "角色管理"
# 连接数据库
conn = pymysql.connect(**db_config)
cursor = conn.cursor()
# 查询所有允许模糊搜索的列
cursor.execute("""
SELECT TABLE_NAME, COLUMN_NAME
FROM INFORMATION_SCHEMA.COLUMNS
WHERE TABLE_SCHEMA = %s AND DATA_TYPE IN ('varchar', 'text')
""", (db_config["db"],))
matching_tables = set()
for table, column in cursor.fetchall():
# 构造模糊搜索的SQL
sql_query = f"SELECT * FROM `{table}` WHERE `{column}` LIKE %s LIMIT 1"
# 执行查询
cursor.execute(sql_query, ('%' + search_keyword + '%',))
# 如果有结果,说明该表有匹配项
if cursor.fetchone():
matching_tables.add(table)
print(f"表 {table} 的 {column} 列中找到了关键词 '{search_keyword}'")
# 关闭连接
cursor.close()
conn.close()
if matching_tables:
print("以下表中包含关键词:", ", ".join(matching_tables))
else:
print("没有找到包含关键词的表。")