Python的Mysql connector封装
2019-07-23 来源:open-open
[Python]代码
#!/usr/bin/env python #-*- coding:utf-8-*- from mysql import connector def connect(): config={ 'host':'localhost',#默认127.0.0.1 'user':'root', 'password':'1111111', 'port':3306 ,#默认即为3306 'database':'test', 'charset':'utf8'#默认即为utf8 } try: return connector.connect(**config) except connector.Error as e: print('connect fail! {}'.format(e)) def execSql(cur, sql, data, isCommit = False): cur.executemany(sql, data) if isinstance(data, list) else cur.execute(sql, data) if isCommit: conn.commit() def insert(conn, tableName, datas): sql = 'insert into `{0}` ({1}) values ({2})' keys = [] placeHolders = [] data = datas if isinstance(datas, list): data = datas[0] for key in data: keys.append(key) placeHolders.append('%('+key+')s') sql = sql.format(tableName, ','.join(keys), ','.join(placeHolders)) id = -1 try: cur = conn.cursor() execSql(cur, sql, datas) if not isinstance(datas, list): id = cur.lastrowid #返回主键 conn.commit() except connector.Error as e: raise e finally: cur.close() return id def query(conn, sql, datas): try: cur = conn.cursor() cur.execute(sql, datas) except connector.Error as e: raise e return cur if __name__ == '__main__': testDict = { 'aa': 1, 'bb': 'aaa', 'cc': 'bbb', 'dd': 'ccc' } conn = connect() print insert(conn, 'test_table', brandDict)
标签: [db:TAGG]
版权申明:本站文章部分自网络,如有侵权,请联系:west999com@outlook.com
特别注意:本站所有转载文章言论不代表本站观点!
本站所提供的图片等素材,版权归原作者所有,如需使用,请与原作者联系。
下一篇:iOS 动画退出应用代码
最新资讯
热门推荐