经常用到MySQL数据库,最近学着用Python操作数据库,在网上看了一些资料,整理了一份适合自己的,记录一下,免得过段时间忘记了。
- 创建表时,自增的主键 id。
- 循环插入数据。
#!/usr/bin/env python #-*-coding:UTF-8-*- import MySQLdb import time def dbConnection(): """数据库的连接""" try: #建立和数据库系统的连接 conn = MySQLdb.connect(host=‘localhost‘, port=3306, user=‘root‘, passwd=‘123456‘, db=‘test) cursor = conn.cursor() #获取操作游标 except MySQLdb.Error,e: print "Mysql Error %d: %s" % (e.args[0], e.args[1]) return conn, cursor def dbClose(conn, cursor): """关闭数据库的连接""" try: #关闭连接,释放资源 conn.commit() cursor.close() conn.close() except MySQLdb.Error,e: print "Mysql Error %d: %s" % (e.args[0], e.args[1]) return True def createTable(sql): """创建表""" a = 0.5 conn, cursor = dbConnection() a = cursor.execute(sql) dbClose(conn, cursor) return a def insertData(): """插入数据""" a = 0.5 conn, cursor = dbConnection() #主键id是自增的,插入时用空字符串代替 values = [(‘‘,‘title ‘+str(i+1), ‘content ‘+str(i+1), time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())) for i in xrange(5)] a = cursor.executemany(‘insert into article values(%s,%s,%s,%s)‘,values) print "insert datas:",a b = cursor.rowcount print b dbClose(conn, cursor) if __name__ == ‘__main__‘: createTableSQL = """create table article( id INT PRIMARY KEY AUTO_INCREMENT, title TEXT, content TEXT, post_on DATETIME )""" print createTable(createTableSQL) value = (‘‘, ‘title 1‘, ‘content 111‘, time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())) print insertData()