Python的Mysql connector封装详解编程语言

[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)

原创文章,作者:ItWorker,如若转载,请注明出处:https://blog.ytso.com/8116.html

(0)
上一篇 2021年7月18日
下一篇 2021年7月18日

相关推荐

发表回复

登录后才能评论