python小技巧大应用--测试通过pymysql实现数据库CRUD
最近买的代码是通过records实现的对mysql数据库的增加和查询工作,不过有可能是我的环境问题,总之报各种错,最终决定不再纠结records,还是使用pymysql对数据库进行CRUD操作.1.通过Navicat 建个简单的数据库test-pythondata,及数据库表userinfo 用于测试1)建数据库test-pythondata2)建表userinfoCREATE TABLE `us
·
最近买的代码是通过records实现的对mysql数据库的增加和查询工作,不过有可能是我的环境问题,总之报各种错,最终决定不再纠结records,还是使用pymysql对数据库进行CRUD操作.
1.通过Navicat 建个简单的数据库test-pythondata,及数据库表userinfo 用于测试
1)建数据库test-pythondata
2)建表userinfo
CREATE TABLE `userinfo` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`name` varchar(50) DEFAULT NULL,
`age` int(11) DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8;
2.通过pymysql对数据库表进行CRUD的测试代码如下:
import pymysql
#----gtj 连接mysql数据库
connect = pymysql.connect(host='localhost',
port=3306,
user='pubuser', #连接数据库名称
password='123321', #连接数据库密码
db='test-pythondata', #数据库名称
charset='utf8')
#----获取光标
cursor = connect.cursor()
# 单条插入
insert_sql = "insert into userinfo (name,age) values (%s,%s)"
try:
cursor.execute(insert_sql,('gtj',33))
connect.commit()
print(u'更新成功...')
except Exception as e:
print(u'更新错误...', e)
connect.rollback()
# finally:
# cursor.close()
# connect.close()
# 批量插入
users_add = [('gtj1',11),('gtj2',22)] # 注意每个list的内容要用括号扩起来
insert_sql = "insert into userinfo (name,age) values (%s,%s)"
# cursor_ins = connect.cursor() # 获取光标
try:
# 注意这里使用的是executemany而不是execute,下边有对executemany的详细说明
cursor.executemany(insert_sql, users_add)
connect.commit()
print(u'更新成功...')
except Exception as e:
print(u'更新错误...', e)
connect.rollback()
# finally:
# cursor.close()
# connect.close()
# 查询userinfo表中数据
select_sql = "SELECT * from userinfo"
cursor.execute(select_sql)
print(u'查询成功...')
datas = cursor.fetchall() #获取查询结果
for data in datas:
print(data)
# 修改
update_sql = "UPDATE userinfo SET age = 50 WHERE `name` = 'gtj'"
cursor.execute(update_sql)
connect.commit()
print(u'修改成功...')
# 删除
delete_sql = "DELETE from userinfo WHERE `name` = 'gtj2'"
rows = cursor.execute(delete_sql)
print("待更新行数:" + str(rows))
connect.commit()
print(u'删除成功...')
cursor.close() #关闭光标
connect.close() #关闭连接
执行结果如图:
总结:注意插入单条,多条记录的执行方法不同
更多推荐
已为社区贡献2条内容
所有评论(0)