Python的DB-API,为大多数的数据库实现了接口,使用它连接各数据库后,就可以用相同的方式操作各数据库。
# -*- encoding: utf-8 -*-import MySQLdbtestdb=MySQLdb.connect(host="localhost", user = "root", passwd="1234",port = 3306,charset="utf8")testdb.select_db("test")cur = testdb.cursor() # 获取游标Title = "Title test"PublishTime = "2015-12-15 05:18:00"Keyword = "乌镇"sql = "INSERT INTO test.news(Title, PublishTime, Keyword) VALUES (%s,%s,%s)"try:cur.execute(sql,(Title, PublishTime, Keyword))testdb.commit()except Exception,e:# Rollback in case there is any errortestdb.rollback()print etestdb.commit()# 关闭连接cur.close()testdb.close()127.0.0.1 localhost ::1 localhost注释掉# -*- encoding: utf-8 -*-连接时的编码设置connect=MySQLdb.connect(host="localhost", user = "root", passwd="1234",port = 3306,charset="utf8")本文永久更新链接地址