# 功能说明 :
# 在指定的目录中查找到trim(XXX)之类的语句,然后取出XXX,
# 在数据库中查找XXX对应的类型是int型的数据
# 日期:2023年3月8日13:25:53
import os
import re
import mysql.connector
import configparser
# 定义正则表达式, 用来匹配trim(XXX)之前的单词
pattern = re.compile(r'trim\(\w+\)')
# 遍历文件夹
def traverse_folder(folder_path):
result = []
for root, dirs, files in os.walk(folder_path):
for file in files:
if file.endswith('.java'):
# 排队了指定的文件
if file == 'FundMoveDataService.java':
break
file_path = os.path.join(root, file)
# 以uft-8的编码打开文件
with open(file_path, 'r', encoding='utf-8') as f:
content = f.read()
# 使用正则表达式匹配字符串
match = pattern.findall(content)
if match:
# 将匹配到的内容放到列表中
result.extend(match)
# 将反斜杆替换成两个反斜杆
result = [x.replace('\\', '\\\\') for x in result]
return result
def GetDBConfig():
# 创建ConfigParser对象
config = configparser.ConfigParser()
# 读取配置文件
config.read('config.ini')
# 获取配置项的值
username = config.get('user', 'username')
password = config.get('user', 'password')
host = config.get('database', 'host')
port = config.get('database', 'port')
database = config.get('database', 'database')
return username, password, host, port, database
def GetExcuteSQL():
querysql = '''
select
data_type,
column_name
from (
select
distinct data_type,
column_name
from
information_schema.columns t
where
TABLE_SCHEMA
in ('fund60pub', 'fund60query', 'fund60trans1', 'fund60trans2', 'fund60acco1', 'fund60acco2')
and lower(t.COLUMN_NAME) in (#content) ) a
where
DATA_TYPE like '%int%'
'''
return querysql
def WriteFile():
global file, item
# 打开文件,指定文件名和打开模式
file = open("my_file.txt", "w")
# 将字符串写入文件
for itemlist in myresult:
file.write(" ".join([item for item in itemlist]))
file.write("\n")
# 关闭文件
file.close()
# 测试
if __name__ == '__main__':
folder_path_in = r'E:\TA6SVN\Sources\ta\fund\server'.replace('\\', '\\\\')
print("检查的文件路径:")
print(folder_path_in)
# 去重
result_in = set(traverse_folder(folder_path_in))
# 去掉trim,及左右的括号
result_single = [x.replace('trim', '').replace('(', '').replace(')', '') for x in result_in]
print("查找到的字段如下:")
print(result_single)
# 获取数据库配置
username, password, host, port, database = GetDBConfig()
# 连接数据库
mydb = mysql.connector.connect(
host=host,
user=username,
password=password,
database=database
)
# 执行SQL查询
querysql = GetExcuteSQL()
# 查询到的内容组成一个字符串,用单引号括起来,并用逗号分开
querysql = querysql.replace('#content', ', '.join([f"'{item}'" for item in result_single]))
print("查询语句如下:")
print(querysql)
# 创建游标对象
cursor = mydb.cursor()
cursor.execute(querysql)
# 获取查询结果
myresult = cursor.fetchall()
# 结果输出
print("检查的结果如下:")
for itemlist in myresult:
print(" ".join([item for item in itemlist]))
# 结果写入文件
WriteFile()
config.ini
[user]
username = AAAAA
password = AAAAA
[database]
host = AAAAA
port = 3306
database = AAAAA