xmysql.py 6.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158
  1. # update: 2023-11-12-19
  2. """
  3. pip install pymysql==0.9.3 -i https://pypi.tuna.tsinghua.edu.cn/simple
  4. pip install SQLAlchemy==1.4.30 -i https://pypi.tuna.tsinghua.edu.cn/simple
  5. 问题:
  6. CryptographyDeprecationWarning: Python 3.6 is no longer supported by the Python core team. Therefore, support for it is deprecated in cryptography. The next release of cryptography will remove support for Python 3.6.
  7. from cryptography.hazmat.backends import default_backen
  8. 解决:
  9. pip3 install cryptography==3.4.8
  10. see: https://blog.csdn.net/weixin_46281427/article/details/122916870
  11. # --- 解决root密码中包含@的问题
  12. self.mysql_dwd_config = {
  13. 'drivername': 'mysql+pymysql',
  14. 'username': 'user_a',
  15. 'password': 'xxx@#$xxx',
  16. 'host': 'am-xxxxx.ads.aliyuncs.com',
  17. 'port': 3306,
  18. }
  19. if sqlalchemy.__version__ >= '1.4': #其实大于1.4.15之后,密码里面含有@,就必须以这种方式创建正确正则识别密码的引擎了。
  20. self.mysql_engine_url = sqlalchemy.engine.URL.create(**self.mysql_dwd_config)
  21. self.mysql_engine_url = self.mysql_engine_url.update_query_dict({'charset': 'utf8mb4'})
  22. else:
  23. # password 含有@
  24. self.mysql_engine_url = '{drivername}://{username}:{password}@{host}:{port}/?charset=utf8mb4'.format(**self.mysql_dwd_config)
  25. self.mysql_dwd_engine = sqlalchemy.create_engine(self.mysql_engine_url)
  26. """
  27. from sqlalchemy import create_engine, inspect, MetaData, Table
  28. from sqlalchemy.orm import sessionmaker
  29. class Client():
  30. def __init__(self, host='127.0.0.1', port=3306, database='ar', username='root', password='20221212!'):
  31. """
  32. """
  33. # 设置字符集
  34. args = 'charset=utf8mb4'
  35. # 设置关闭 only_full_group_by 模式
  36. args = '&sql_mode=STRICT_TRANS_TABLES,NO_ZERO_IN_DATE,NO_ZERO_DATE,ERROR_FOR_DIVISION_BY_ZERO,NO_ENGINE_SUBSTITUTION'
  37. self.engine = create_engine(f"mysql+pymysql://{username}:{password}@{host}:{port}/{database}?{args}")
  38. # self.engine = create_engine(f"mysql+pymysql://{username}:{password}@{host}:{port}/{database}")
  39. self.database = database
  40. self.inspect = inspect(self.engine)
  41. def get_all_database(self):
  42. """获取全部数据库名称"""
  43. return self.inspect.get_schema_names()
  44. def get_all_table(self, database_name):
  45. """获取全部数据表名称"""
  46. return self.inspect.get_table_names(schema=database_name)
  47. def get_all_field(self, table_name):
  48. """获取全部字段名称"""
  49. fields = self.inspect.get_columns(table_name, schema=self.database) # 表名,库名
  50. return [i.get('name') for i in fields]
  51. def execute_sql(self, sql):
  52. """
  53. 执行sql
  54. """
  55. try:
  56. result = self.engine.execute(sql).fetchone()[0]
  57. # print(result.__class__.__name__)
  58. return result
  59. except Exception as exception:
  60. print(exception.__class__.__name__)
  61. return None
  62. def get_all(self, table_name):
  63. """
  64. 获取全部数据
  65. """
  66. sql = f"SELECT * FROM {table_name};"
  67. try:
  68. result = self.engine.execute(sql).fetchall() # 返回的是列表
  69. # print(result.__class__.__name__)
  70. return result
  71. except Exception as exception:
  72. print(exception.__class__.__name__)
  73. return None
  74. def get_one(self, table_name='ar_user', where_key='ACCT', where_val='admin'):
  75. """
  76. 单条获取
  77. """
  78. sql = f"SELECT * FROM {table_name} WHERE {where_key} = '{where_val}';"
  79. try:
  80. result = self.engine.execute(sql).fetchone() # 返回的是元祖
  81. # result = self.engine.execute(sql).fetchall() # 返回的是列表
  82. # print(result.__class__.__name__)
  83. return result
  84. except Exception as exception:
  85. print(exception.__class__.__name__)
  86. return None
  87. if __name__ == '__main__':
  88. # --- init ---
  89. # db = Client(host='127.0.0.1', port=3306, database='ar', username='root', password='20221212!')
  90. db = Client(host='127.0.0.1', port=3306, database='ar', username='root', password='rootroot&123123')
  91. # db = Client(host='58.34.94.176', port=8806, database='ar', username='root', password='rootroot&123123')
  92. # --- test ---
  93. # result = db.get_all_field('ar_user')
  94. # result = db.get_all('ar_phone_call')
  95. result = db.get_one('ar_user', 'USER_ID', '10000LXQ')
  96. print(result)
  97. print(result[1])
  98. # --- test ---
  99. # sql = f'''select a.USER_ID, a.USER_NAME, a.EMP_NO, a.PHOTO, a.PHONE, c.DEPT_ID, c.DEPT_NAME, e.ROLE_ID, e.ROLE_NAME, a.IS_DISABLED
  100. # from ar_user a left JOIN ar_user_dept_rel b ON a.USER_ID = b.USER_ID
  101. # left join ar_dept c on c.DEPT_ID = b.DEPT_ID
  102. # left join ar_user_role_rel d on a.USER_ID = d.USER_ID
  103. # left join ar_role e on d.ROLE_ID = e.ROLE_ID
  104. # where a.ACCT = 'admin'
  105. # '''
  106. # sql = f'''select a.USER_ID, a.USER_NAME, a.EMP_NO, a.PHOTO, a.PHONE, c.DEPT_ID, c.DEPT_NAME, e.ROLE_ID, e.ROLE_NAME, a.IS_DISABLED
  107. # from AR_USER a left JOIN AR_USER_DEPT_REL b ON a.USER_ID = b.USER_ID
  108. # left join AR_DEPT c on c.DEPT_ID = b.DEPT_ID
  109. # left join AR_USER_ROLE_REL d on a.USER_ID = d.USER_ID
  110. # left join AR_ROLE e on d.ROLE_ID = e.ROLE_ID
  111. # where a.ACCT = 'admin'
  112. # '''
  113. # out = db.engine.execute(sql).fetchone()
  114. # print(out)
  115. # --- test ---
  116. # result = db.get_all_field('ar', 'ar_user')
  117. # print(result)
  118. # --- test ---
  119. # result = db.get_one()
  120. # result = db.get_one(table_name='ar_user', where_key='USER_NAME', where_val='陈旭')
  121. # result = db.get_one(table_name='ar_user', where_key='USER_NAME', where_val='admin')
  122. # print(result)
  123. # --- test ---
  124. # sql = f'''select count(1) from ar.ar_phone_call where status in (0, 1)'''
  125. # result = db.execute_sql(sql)
  126. # print(result)
  127. # --- test ---
  128. # items = db.get_all('vul_detail')
  129. # for item in items:
  130. # print(item.cve_id)
  131. # # print(item.vul_name)
  132. # --- test ---
  133. # out = db.get_one('vul_detail', {'cve_id': 'CVE-2007-1858'})
  134. # print(type(out.get('cvss_point')))
  135. # print(out.get('cvss_point'))