PyMySQL是在Python3。x版本中用于连接MySQL云服务器的一个库,Python2中则使用mysqldb
话不多说,直接上代码来说明用途
# !/user/bin/env python
# utf - 8编码=
从pymysql进口连接,游标从pymysql
。犯错进口OperationalError
导入操作系统
进口configparser cparser
从内置进口int
框架。记录器导入日志记录器
导入时间
& # 39; & # 39; & # 39;
========读取config.ini文件中mysql配置========
& # 39; & # 39; & # 39;
base_dir=str (os.path.dirname (os.path.dirname(强> <强>文件)))
file_path=base_dir +“\ config \ config.ini"
cf=configUtil (file_path)
主机=cf.get (“sitmysqlconf",“host")
=cf.get港(“sitmysqlconf" & # 39;港口# 39;)
db=cf.get (“sitmysqlconf" & # 39; db_name& # 39;)
用户=cf.get (“sitmysqlconf" & # 39;用户# 39;)
密码=cf.get (“sitmysqlconf" & # 39;密码# 39;)
记录器=记录器(logger=癿ysqlUtils") .getlog ()
& # 39; & # 39; & # 39;
===========封装mysql基本操作=============
& # 39; & # 39; & # 39;
类mysqlUtils:
<代码> def __init__(自我): ,,& # 39;& # 39;& # 39; ,mysql,初始化获得连接 ,,& # 39;& # 39;& # 39; ,,试一试: ,,,自我。康涅狄格州=连接(主机=主机, ,,,,,,,,,,,,,,端口=int(端口), ,,,,,,,,,,,,,,用户=用户, ,,,,,,,,,,,,,=密码,密码, ,,,,,,,,,,,,,,db=db, ,,,,,,,,,,,,,,charset=& # 39; utf8mb4& # 39; ,,,,,,,,,,,,,cursorclass=cursors.DictCursor ,,,,,,,,,,,,,,) ,,除了OperationalError e: ,,,,打印(e) def光标(自我): ,,& # 39;& # 39;& # 39; ,,获得游标 ,,& # 39;& # 39;& # 39; ,,self.conn.cursor () def getDict(自我、表名、systemID ColumnNameKey, ColumnNameValue): ,,& # 39;& # 39;& # 39; ,,公共方法,获取id的字典 ,,& # 39;& # 39;& # 39; ,,与self.conn.cursor光标(): ,,,,cursor.execute (“select *,从% s system_id=%和% s=% s",(表、systemID ColumnNameKey, ColumnNameValue)) ,,Dict=cursor.fetchone () ,,self.conn.commit () ,,返回Dict类型 ,,def AttentionLibraryDelete(自我、system_id merchant_id): ,,& # 39;& # 39;& # 39;非正常删除数据,即直接操作数据库删除& # 39;& # 39;& # 39; ,,与self.conn.cursor光标(): ,,,,cursor.execute(“删除,从表system_id=% s和merchant_id=% s;“, (system_id merchant_id)) ,,self.conn.commit () ,,,def addMerchantTOIT(自我,merchant_id): ,,& # 39;& # 39;& # 39;把商家关联到XXX行业中& # 39;& # 39;& # 39; ,,# realSQL=安迦氡?system_id, merchant_id business_id、状态、creator_id create_date, updater_id, update_date)值(& # 39;7 b6a99f3bce14915863cde5104bdf2c3& # 39; % s, & # 39; 11 & # 39;, & # 39;一个# 39;,& # 39;8 & # 39;,unix_timestamp(现在())* 1000,& # 39;8 & # 39;,unix_timestamp(现在())* 1000);“repr (merchant_id, %) ,,与self.conn.cursor光标(): ,,,,cursor.execute(“插入t_sys_merchant_business (system_id, merchant_id business_id、状态、creator_id create_date, updater_id, update_date)值(& # 39;7 b6a99f3bce14915863cde5104bdf2c3& # 39; % s, & # 39; 11 & # 39;, & # 39;一个# 39;,& # 39;8 & # 39;,unix_timestamp(现在())* 1000,& # 39;8 & # 39;,unix_timestamp(现在())* 1000);“,(merchant_id)) ,,self.conn.commit () ,,logger.info(& # 39;把商家【% s】关联到xxx成功& # 39;% merchant_id) 代码>
def关闭(自我):
& # 39; & # 39; & # 39;
关闭mysql数据库,,,,
& # 39; & # 39; & # 39;
self.conn.close ()