mysqlutil.py 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192
  1. #!/usr/bin/python
  2. # -*- coding:utf-8 -*-
  3. import sys
  4. import os
  5. sys.path.append(os.path.abspath('..'))
  6. from util.config import config
  7. import pymysql
  8. from sqlalchemy import create_engine
  9. class MysqlConfig(object):
  10. HOST = config.get('mysql', 'host')
  11. USER = config.get('mysql', 'user')
  12. PASSWORD = config.get('mysql', 'password')
  13. DB = config.get('mysql', 'db')
  14. engine = create_engine('mysql+pymysql://{}:{}@{}/{}?charset=utf8'.format(
  15. MysqlConfig.USER,
  16. MysqlConfig.PASSWORD,
  17. MysqlConfig.HOST,
  18. MysqlConfig.DB,
  19. ))
  20. class Mysql(object):
  21. def __init__(self):
  22. # 数据库构造函数,从连接池中取出连接,并生成操作游标
  23. # self._conn = Mysql.__GetConnect()
  24. self.host = MysqlConfig.HOST
  25. self.user = MysqlConfig.USER
  26. self.pwd = MysqlConfig.PASSWORD
  27. self.db = MysqlConfig.DB
  28. __pool = None
  29. # @staticmethod
  30. def __GetConnect(self):
  31. """
  32. @summary: 静态方法,从连接池中取出连接
  33. @return MySQLdb.connection
  34. """
  35. if not self.db:
  36. raise (NameError, "没有设置数据库信息")
  37. self.conn = pymysql.connect(host=self.host, user=self.user, password=self.pwd, database=self.db)
  38. db= self.conn
  39. if not db:
  40. raise (NameError, "连接数据库失败")
  41. else:
  42. return db
  43. def insert_batch(self, sql, data):
  44. db = self.__GetConnect()
  45. cur = db.cursor()
  46. try:
  47. cur.executemany(sql, data)
  48. db.commit()
  49. except Exception as e:
  50. db.rollback()
  51. print(e)
  52. finally:
  53. cur.close()
  54. db.close()
  55. def select_list(self, sql):
  56. db = self.__GetConnect()
  57. cur = db.cursor(cursor=pymysql.cursors.DictCursor)
  58. results = []
  59. try:
  60. cur.execute(sql)
  61. results = cur.fetchall()
  62. db.commit()
  63. # print(results)
  64. except Exception as e:
  65. print(e)
  66. finally:
  67. cur.close()
  68. db.close()
  69. return results
  70. if __name__ == '__main__':
  71. sql = 'select name from `ai-callcenter-dev`.callcenter_ai_terminology limit 10'
  72. mysql = Mysql()
  73. result = mysql.select_list(sql)
  74. for item in result:
  75. print(item['name'])