标签:import err charset insert sql查询 事务机制 value hal rop
import pymysql
db = pymysql.connect("localhost","root","","hank") #打开数据库 (如果连接失败会报错)
cursor = db.cursor() #获取游标对象
sql_select = "select version()" #执行sql查询操作
cursor.execute(sql_select)
1
data = cursor.fetchone() #使用fetchone()获取单条数据
print("DB version is : %s" % data)
DB version is : 5.6.39
cursor.execute("drop table if exists hankleo") #如果hankleo表存在,就删除
0
#创建表hankleo
sql_create = "create table hankleo(id int,name varchar(10)) engine = innodb charset = utf8"
cursor.execute(sql_create)
0
#插入操作
sql_insert = ‘‘‘insert into hankleo(id,name) values(2,"李明")‘‘‘
try:
#执行sql
cursor.execute(sql_insert)
db.commit()
except:
#发生异常
db.rollback()
#查询操作
sql_select = ‘‘‘select * from hankleo‘‘‘
try:
#执行sql语句
cursor.execute(sql_select)
#获取所有记录列表
result = cursor.fetchall()
for row in result:
id = row[0]
name = row[1]
print("id = %d,name = %s" % (id,name))
except:
print("Error:unable to fecth data")
id = 2,name = 李明
事务机制可以确保数据的一致性
#例子
sql_insert = ‘‘‘insert into hankleo (id,name) values (1,‘china‘)‘‘‘
try:
cursor.execute(sql_insert)
db.commit()
except:db.rollback()
print("end")
#关闭连接
db.close()
end
标签:import err charset insert sql查询 事务机制 value hal rop
原文地址:https://www.cnblogs.com/hankleo/p/9551720.html