# -*- 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()
连接过程可能出现的问题:
2003, “Can’t connect to MySQL server on ‘localhost’ (10061)” a、该问题的原因有可能是MySQL本地服务的问题,这种情况下只要检查下本地服务中相应的服务有没有开启即可; b、另一种情况是由于hosts文件中的设置的localhost对应的IP不对,检查一下,设置为 127.0.0.1 localhost 即可,并且将这一行 ::1 localhost注释掉