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
| import json from tkinter import * from tkinter import messagebox import win32con import win32clipboard import re
def set_text(string): win32clipboard.OpenClipboard() win32clipboard.EmptyClipboard() win32clipboard.SetClipboardData(win32con.CF_UNICODETEXT, string) win32clipboard.CloseClipboard()
def to_snake_case(x): return re.sub('(?<=[a-z])[A-Z]|(?<!^)[A-Z](?=[a-z])', '_\g<0>', x).lower()
root = Tk() root.title("Json转MySQL建表语句") root.geometry('300x150') l1 = Label(root, text="表名:") l1.pack() v_json_title = StringVar() title = Entry(root, textvariable=v_json_title) v_json_title.set("") title.pack() l2 = Label(root, text="Json:") l2.pack() v_json_str = StringVar() sstr = Entry(root, textvariable=v_json_str) v_json_str.set("") sstr.pack()
def on_click(): json_title = v_json_title.get() json_str = v_json_str.get() data = json.loads(json_str) sql = "CREATE TABLE `" + json_title + "` (\n `id` bigint(20) NOT NULL AUTO_INCREMENT COMMENT 'ID',\n" \ " `parent_id` bigint(20) NOT NULL COMMENT '父ID',\n" for item in data: if isinstance(data[item], int): if len(str(data[item])) < 15: sql += " `" + to_snake_case(item) + "` bigint(20) NULL DEFAULT NULL,\n" elif len(str(data[item])) >= 15: sql += " `" + to_snake_case(item) + "` bigint(" + str(len(str(data[item])) * 2) + ") NULL DEFAULT NULL,\n" elif isinstance(data[item], str): if len(data[item]) < 50: sql += " `" + to_snake_case(item) + "` varchar(100) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL,\n" elif 50 <= len(data[item]) < 200: sql += " `" + to_snake_case(item) + "` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL,\n" elif len(data[item]) >= 200: sql += " `" + to_snake_case(item) + "` varchar(" + str( len(data[item]) * 2) + ") CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL,\n" elif isinstance(data[item], float): sql += " `" + to_snake_case(item) + "` decimal(15,3) NULL DEFAULT NULL,\n" elif isinstance(data[item], float): sql += " `" + to_snake_case(item) + "` bigint(1) NULL DEFAULT NULL,\n" else: print(data[item]) sql += " PRIMARY KEY (`id`) USING BTREE\n" \ ") ENGINE = InnoDB AUTO_INCREMENT = 1 CHARACTER SET = utf8 COLLATE = utf8_general_ci ROW_FORMAT = Compact;" set_text(sql) messagebox.showinfo(title='处理成功', message="数据已经添加进剪贴板") print(sql)
Button(root, text="转换", command=on_click).pack() root.mainloop()
|