数据以元组的方式存入MySQL数据库

因为工作中涉及到存入MySQL数据库,今天作者在这里分享一个简单的MySQL多条插入元组的方法,直接上代码了:

# coding=utf-8

try:
    import MySQLdb as mysqldb
    from MySQLdb import InternalError
except ImportError:
    import pymysql as mysqldb
    from pymysql.err import InternalError

conn_instance_dict = {}

DB_CONFIG = {
    # 'host':'IP', 'port' : 3306, 'user':'自己密码', 'passwd':'666',
    'host': 'IP', 'port': 3306, 'user': '自己账号', 'passwd': '888',
    'charset': 'utf8',
    'db': 'test',
}


def _newConn(db):
    DB_CONFIG.update(db=db)
    conn = mysqldb.connect(**DB_CONFIG)
    return conn

def getConn(db):
    try:
        conn = conn_instance_dict[db]
        conn.ping()
        return conn
    except (InternalError, KeyError):
        conn = _newConn(db)
        conn_instance_dict[db] = conn
        return conn

def insertDB(data, db, table):
    if not data:
        return
    try:
        conn = getConn(db)
    except BaseException as e:
        print e
    cur = conn.cursor()
    if isinstance(data, tuple):
        params = ','.join(['%s'] * len(data))
        sql = 'insert into %s()' \
              'values(%s) ' % (table, params)
        cur.execute(sql, data)
    else:
        params = ','.join(['%s'] * len(data[0]))
        sql = 'insert into %s()'\
              'values(%s) ' % (table, params)
        try:
            cur.executemany(sql, data)
        except Exception, e:
            print e
            print sql
    cur.close()
    conn.commit()


if __name__ == '__main__':
    print _newConn('test')

以上的代码首先声明作者插入MySQL的时候,数据的格式如下几类:

(1,2,3)
[(1,2,3)]
((1,2,3))

好了,做的一个简单的分享吧,如有错误,欢迎前来纠正。

你可能感兴趣的:(python)