下载安装MySQLdb
python代码
- # -*- coding: utf-8 -*-
- #mysqldb
- import time, MySQLdb,sys
- reload(sys)
- sys.setdefaultencoding('utf-8')
- #连接
- conn=MySQLdb.connect(host="localhost",user="root",passwd="",db="test",charset="utf8")
- cursor = conn.cursor()
- #写入
- songs = ('Purple Haze', 'All', 'Foxy Lady')
- for song in songs:
- cursor.execute("INSERT INTO user (name,created) VALUES (%s,1212321)", song)
- print "Auto Increment ID: %s" % cursor.lastrowid
- conn.commit()
- cursor.close()
- #关闭
- conn.close()
这里需要特别注意一点当数据库选择innodb时 python mysqldb 把autocommit自动改成off ,所以每次insert时,最后都要commit