Python向mysql数据库插入数据

一、向表tcolor中插入数据的主要流程如下:

import datetime

import pymysql.cursors

connection = pymysql.connect(host='localhost', port=3306, user='root', password='11111', db='users', charset='utf8', cursorclass=pymysql.cursors.DictCursor)

Url = "http://www.baidu.com"
Time = datetime.datetime.now() # 系统当前时刻

sql = "insert into color(url, time) values('%s','%s')" % (Url,Time)

try:
cursor = connection.cursor()
cursor.execute(sql)
connection.commit()
except Exception:
print("查询失败!!!")

cursor.close()
connection.close()

二、Python向mysql逐条插入数据一般有两种形式:

sql = "insert into color(url, time) values('%s','%s')" % (Url,Time)
cursor = db.cursor()
try:
cursor.execute(sql)
db.commit() #提交到数据库执行,一定要记提交哦
except Exception,e:
db.rollback() #发生错误时回滚
print e
cursor.close()

------------------------------------------------------------------------------------------------------

sql = "insert into color(url, time) values(%s,%s)" #注意此处与前一种形式的不同
par = (Url,Time)
cursor = db.cursor()
try:
cursor.execute(sql,par)
db.commit() #提交到数据库执行,一定要记提交哦
except Exception,e:
db.rollback() #发生错误时回滚
print e
cursor.close()

上一篇:MySQL数据库插入数据出现 ERROR 1526 (HY000): Table has no partition for value xxx


下一篇:bootstrap的popover在trigger设置为hover时不隐藏popover