七仔的博客

七仔的博客GithubPages分博

0%

python通过数据库自动生成SSM代码

思路是做一个模板,然后读取数据库结构,最后生成代码包。

python通过数据库自动生成SSM代码

前段时间要写几个差不多的项目,后天都是用的SSM,然后用ajax通信,就先敲了个这个出来。

思路是做一个模板,然后读取数据库结构,最后生成代码包。

因为比较着急,也没细做,先放到这,后面有时间了完善一下。

主模块

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
#!/usr/bin/python3
import mysql
import file
import template

db_name = "*" # 数据库名


if __name__ == '__main__':
# 连接数据库读取表列表
table_list = mysql.get_table_list(db_name)
# 获取代码模板
template_list = file.get_template_list()
for table in table_list:
# 获取表结构
table_struct_list = mysql.get_table_struct(table, db_name)
# 对代码模板进行加工
code_gen_list = template.handle(table, table_struct_list, template_list)
# 输出成品代码
file.save_code_gen(table, code_gen_list)

文件模块

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
#!/usr/bin/python3
import os
import template

# 代码模板列表
template_baseJavaWeb_path_list = [
"template-baseJavaWeb/bean/Base.java",
"template-baseJavaWeb/controller/BaseController.java",
"template-baseJavaWeb/dao/BaseMapper.java",
"template-baseJavaWeb/mapping/BaseMapper.xml",
"template-baseJavaWeb/service/BaseService.java",
"template-baseJavaWeb/serviceImpl/BaseServiceImpl.java"
]
# template_ssm_manage_path_list = [
# "template-ssm-manage/controller/BaseController.java",
# "template-ssm-manage/mapper/BaseMapper.java",
# "template-ssm-manage/mapper/BaseMapper.xml",
# "template-ssm-manage/service/BaseService.java",
# "template-ssm-manage/po/Base.java"
# ]
# template_permission_path_list = [
# "template-permission/controller/BaseController.java",
# "template-permission/mapper/BaseMapper.java",
# "template-permission/mapper/BaseMapper.xml",
# "template-permission/pojo/Base.java",
# "template-permission/service/impl/BaseServiceImpl.java",
# "template-permission/service/BaseService.java"
# ]

template_path_list = template_baseJavaWeb_path_list


def get_template_list():
"""代码模板列表获取

:return: 代码模板列表
"""
template_list = []
for template_path in template_path_list:
with open(template_path, 'r', encoding='UTF-8') as file:
template_list.append(file.read())
print("获取代码模板成功,代码模板路径列表:" + str(template_path_list))
return template_list


def save_code_gen(table_name, code_gen_list):
"""成品代码保存

:param table_name: 表名
:param code_gen_list: 成品代码列表
"""
index = 0
for template_path in template_path_list:
template_folder_path = template_path[:template_path.find("Base")-1]
template_folder_path = template_folder_path.replace("template", "code-gen")
if not os.path.exists(template_folder_path):
os.makedirs(template_folder_path)
template_path = template_path.replace("template", "code-gen")
template_path = template_path.replace("Base", template.line_to_hump(table_name["Name"]))
print("保存路径:" + template_path)
with open(template_path, 'w+', encoding='UTF-8') as file:
file.write(code_gen_list[index])
index = index + 1
print("保存成品代码成功!!!")

数据库模块

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
import pymysql

host = 'localhost'
user = 'root'
password = 'root'


def get_table_list(db_name):
"""连接数据库读取表列表

:return: 数据库表列表
"""
tables = []
connection = pymysql.connect(host=host, user=user, password=password, db=db_name,
charset='utf8', cursorclass=pymysql.cursors.DictCursor)
try:
with connection.cursor() as cursor:
cursor.execute("show table status;")
table = cursor.fetchall() # 获取所有(输出是列表,列表中的每个元素是字典,字典的KEY是Tables_in_拼接数据库名称)
for k in range(len(table)): # 提取表名
tables.append({"Name": table[k]['Name'], "Comment": table[k]['Comment']})
finally:
connection.commit()
connection.close()
print("获取表名成功,[表名,注释]列表:" + str(tables))
return tables


def get_table_struct(table_name, db_name):
"""获取表结构

:param table_name: {Name:表名,Comment:注释}
:return: 表结构
"""
structs = []
connection = pymysql.connect(host=host, user=user, password=password, db=db_name,
charset='utf8', cursorclass=pymysql.cursors.DictCursor)
cursor = connection.cursor()
sql = "show full columns from `" + table_name["Name"] + "`"
cursor.execute(sql) # 查询表结构
for x in cursor:
structs.append(x)
connection.close()
print("获取表结构成功,结构列表:" + str(structs))
return structs

代码生成模块

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
#!/usr/bin/python3
import re
# 模板规则:
# 形如$base$的用表名替换
# 形如$Base$的用表名大驼峰风格替换
# 形如$Note$的用表注释替换
# 形如$for *$(*为长度不一的字符串)的
# 其内有%javaType%的用字段类型转Java类型替换
# 其内有%type%的用字段类型替换
# 其内有%note%的用字段注释替换
# 其内有%name_%的用字段名替换
# 其内有%name%的用字段名(转小驼峰)替换
# 其内有%Name%的用字段名(转大驼峰)替换
# 其内有%in-*%(*为长度不一的字符串)的*用来做列表分隔符,例子:a,b,c中的,
# $for0 *$为列表第一个
# $for+ *$为列表从第二个到最后一个

re_for = r"\$for[a-zA-Z0-9%\-; \n\r\.=\(\)<>{}/\"\*@_,!'#+]+\$"


def line_to_hump(line):
"""下划线风格转为大驼峰

:param line: 下划线风格字符串
:return: 大驼峰风格字符串
"""
if "_" in line:
return "".join(map(lambda x: x.capitalize(), line.split("_")))
return line.capitalize()


def to_little_hump(hump):
"""转为小驼峰

:param line: 大驼峰风格字符串
:return: 小驼峰风格字符串
"""
return hump[0:1].lower() + hump[1:]


def to_type(type):
if "int" in type:
return "INTEGER"
if "double" in type:
return "DOUBLE"
if "varchar" in type:
return "VARCHAR"
if "text" in type:
return "VARCHAR"
if "date" in type:
return "DATE"
if "decimal" in type:
return "DECIMAL"


def to_java_type(type):
if "int" in type:
return "Integer"
if "double" in type:
return "Double"
if "varchar" in type:
return "String"
if "text" in type:
return "String"
if "date" in type:
return "Date"
if "decimal" in type:
return "BigDecimal"


def handle_table_name(table_name, template_list):
"""表名处理

:param table_name: {Name:表名,Comment:注释}
:param template_list: 代码模板
:return: 加工代码
"""
code_gen_list = []
for template in template_list:
print()
template = template.replace("$base$", table_name["Name"])
template = template.replace("$Base$", line_to_hump(table_name["Name"]))
template = template.replace("$Note$", table_name["Comment"])
code_gen_list.append(template)
return code_gen_list


def get_for_handle_list(table_struct, for_sign_list, index, length):
"""列表内处理

:param table_struct: 字段结构
:param index: 循环下标
:param for_sign_list: for模板列表
:return:
"""
for_handle_list = []
for for_sign in for_sign_list:
before_for_sign = for_sign
if "$for0" in for_sign and index != 0:
for_handle_list.append(for_sign)
continue
if "$for+" in for_sign and index == 0:
for_handle_list.append(for_sign)
continue
if "%name_%" in for_sign:
for_sign = for_sign.replace("%name_%", table_struct["Field"])
if "%name%" in for_sign:
for_sign = for_sign.replace("%name%", to_little_hump(line_to_hump(table_struct["Field"])))
if "%Name%" in for_sign:
for_sign = for_sign.replace("%Name%", line_to_hump(table_struct["Field"]))
if "%note%" in for_sign:
for_sign = for_sign.replace("%note%", table_struct["Comment"])
if "%javaType%" in for_sign:
for_sign = for_sign.replace("%javaType%", to_java_type(table_struct["Type"]))
if "%type%" in for_sign:
for_sign = for_sign.replace("%type%", to_type(table_struct["Type"]))
sign = re.search(r"%in-[ ,]+%", for_sign)
if sign:
for_sign = for_sign.replace(sign.group(), ",")
for_sign = for_sign.replace("$for0", "").replace("$for+", "")
for_sign = for_sign.replace("$for", "").replace("$", "")
if index < (length - 1):
for_sign = for_sign + before_for_sign
else:
for_sign = for_sign[::-1]
for_sign = for_sign.replace(",", "", 1)
for_sign = for_sign[::-1]
for_handle_list.append(for_sign)
return for_handle_list


def handle_struct_list(table_struct_list, template_list):
"""列表处理

:param table_struct_list: 表结构列表
:param template_list: 代码模板
:return: 加工代码
"""
code_gen_list = []
for template in template_list:
index = 0
for table_struct in table_struct_list:
# 获取for列表并留下恢复记号
for_sign = re.search(re_for, template)
for_sign_list = []
while for_sign:
for_sign_str = for_sign.group()
for_sign_list.append(for_sign_str)
template = template.replace(for_sign.group(), "^^^", 1)
for_sign = re.search(re_for, template)
# 进行列表内处理
for_handle_list = get_for_handle_list(table_struct, for_sign_list, index, len(table_struct_list))
# 进行恢复替换
for for_handle in for_handle_list:
template = template.replace("^^^", for_handle, 1)
index = index + 1
code_gen_list.append(template)
return code_gen_list


def handle_end(template_list):
"""最后处理

:param template_list: 代码模板
:return: 加工代码
"""
code_handle_list = []
for template in template_list:
for_sign = re.search(re_for, template)
while for_sign:
template = template.replace(for_sign.group(), "")
for_sign = re.search(re_for, template)
code_handle_list.append(template)
code_gen_list = []
for template in code_handle_list:
template = template.replace("$for0", "").replace("$for+", "")
template = template.replace("$for", "").replace("$", "").replace("^^^", "")
code_gen_list.append(template)
return code_gen_list


def handle(table_name, table_struct_list, template_list):
"""总处理函数

:param table_name: {Name:表名,Comment:注释}
:param table_struct_list: 表结构列表
:param template_list: 模板列表
:return: 成品代码列表
"""
code_gen_list = handle_table_name(table_name, template_list)
code_gen_list = handle_struct_list(table_struct_list, code_gen_list)
code_gen_list = handle_end(code_gen_list)
return code_gen_list

这些就是全部代码了,然后还要根据模板规则写个模板,最后运行就可以
这里放上模板和代码,对了还要在项目里加个base包和里面的文件,里面是抽出来的基本增删改查操作,base也放进去了:

点击下载文件

此为博主副博客,留言请去主博客,转载请注明出处:https://www.baby7blog.com/myBlog/64.html

欢迎关注我的其它发布渠道