Python 操作 mysql-插入多条数据

#!/usr/bin/env python
# -*- coding: utf-8 -*-

# 加载模块
import sys
import MySQLdb

# 设置默认编码为UTF-8,否则从数据库
# 读出的UTF-8数据无法正常显示
reload(sys)
sys.setdefaultencoding('utf-8')
T = (('1','1','10','1','10','1','atyu30'), ('2','1','10','1','10','1','atyu30'))

# 连接数据库
conn = MySQLdb.Connection(host="localhost", user="root", passwd="", charset="UTF8")
conn.select_db('test')

# 创建指针,并设置数据的返回模式为字典
cursor = conn.cursor(MySQLdb.cursors.DictCursor)

# 执行SQL
cursor.executemany("insert into page values (%s,%s,%s,%s,%s,%s,%s)", T)

# 关闭指针
cursor.close()

# 关闭数据库连接
conn.close()

源:http://blog.chinaunix.net/uid-20438355-id-61256.html

实际例子:

if __name__=="__main__":
    datas = [(37,'baidu22','baidu200','200','300','400','500','600',2),(37,'baidu22','baidu200','201','301','401','501','601',1)]
    print "11111"
    conn=MySQLdb.connect(host='10.154.156.224',user='root',passwd='scpsql',db='scp',port=3306)
    cursor = conn.cursor()   

    print "2222"   

    sql = "insert into service_chartdata (jmetertask_id,test_name,threadname,timeinterval,responseduration,averageduration,hitspersecond,tps,do_number) values (%s,%s,%s,%s,%s,%s,%s,%s,%s)"
    try:
        print "3333"
        cursor.executemany(sql,datas)
    except Exception as e:
        print "mysql insert error"
    finally:
        cursor.close()
        conn.commit()
        conn.close()