Browse Source

添加sql工具类

tianyun 2 years ago
parent
commit
301e266c7c
4 changed files with 45 additions and 0 deletions
  1. 0 0
      tmp/__init__.py
  2. 0 0
      tmp/mysql/__init__.py
  3. 22 0
      tmp/mysql/sql_util.py
  4. 23 0
      tmp/mysql/test_rxdp_test.py

+ 0 - 0
tmp/__init__.py


+ 0 - 0
tmp/mysql/__init__.py


+ 22 - 0
tmp/mysql/sql_util.py

@@ -0,0 +1,22 @@
+import pymysql
+
+
+class Database:
+    def __init__(self, host, user, password, database):
+        self.connection = pymysql.connect(
+            host=host,
+            user=user,
+            password=password,
+            database=database
+        )
+
+    def query(self, sql):
+        with self.connection.cursor() as cursor:
+            cursor.execute(sql)
+            result = cursor.fetchall()
+        return result
+
+    def execute(self, sql):
+        with self.connection.cursor() as cursor:
+            cursor.execute(sql)
+        self.connection.commit()

+ 23 - 0
tmp/mysql/test_rxdp_test.py

@@ -0,0 +1,23 @@
+import os
+
+from tmp.mysql.sql_util import Database
+
+# 查询所有表
+db = Database('mysql.rxdptest.svc.k5.bigtree.zone', 'test_user', 'tmOxmmc+3jznq2cX', 'dip_message')
+query = db.query(f"SELECT table_name FROM information_schema.tables WHERE table_schema = DATABASE();")
+allTable = set([x[0] for x in query])
+print(allTable)
+
+# 应该有的表
+sql_file_table = set("message_record message_record_detail".split(" "))
+print(sql_file_table)
+
+# 差集
+differenceTable = allTable.difference(sql_file_table)
+print(differenceTable)
+
+# 生产sql
+with open("tmp.sql", "w") as f:
+    for x in differenceTable:
+        f.write(f"DROP TABLE IF EXISTS `{x}`;")
+        f.write(os.linesep)