python3操作mysql数据库增删改查
- #!/usr/bin/python3
- import pymysql
- import types
- db=pymysql.connect("localhost","root","123456","python");
- cursor=db.cursor()
- #创建user表
- cursor.execute("drop table if exists user")
- sql="""CREATE TABLE IF NOT EXISTS `user` (
- `id` int(11) NOT NULL AUTO_INCREMENT,
- `name` varchar(255) NOT NULL,
- `age` int(11) NOT NULL,
- PRIMARY KEY (`id`)
- ) ENGINE=InnoDBDEFAULT CHARSET=utf8 AUTO_INCREMENT=0"""
- cursor.execute(sql)
- #user插入数据
- sql="""INSERT INTO `user` (`name`, `age`) VALUES
- ('test1', 1),
- ('test2', 2),
- ('test3', 3),
- ('test4', 4),
- ('test5', 5),
- ('test6', 6); """
- try:
- # 执行sql语句
- cursor.execute(sql)
- # 提交到数据库执行
- db.commit()
- except:
- # 如果发生错误则回滚
- db.rollback()
- #更新
- id=1
- sql="update user set age=100 where id='%s'" % (id)
- try:
- cursor.execute(sql)
- db.commit()
- except:
- db.rollback()
- #删除
- id=2
- sql="delete from user where id='%s'" % (id)
- try:
- cursor.execute(sql)
- db.commit()
- except:
- db.rollback()
- #查询
- cursor.execute("select * from user")
- results=cursor.fetchall()
- for row in results:
- name=row[0]
- age=row[1]
- #print(type(row[1])) #打印变量类型
- print ("name=%s,age=%s" % \
- (age, name))
【python3操作mysql数据库增删改查】转载于:https://www.cnblogs.com/meng-wei-zhi/p/8214750.html
推荐阅读
- 2.6|2.6 Photoshop操作步骤的撤消和重做 [Ps教程]
- MongoDB,Wondows下免安装版|MongoDB,Wondows下免安装版 (简化版操作)
- 在线版的迅捷思维导图怎么操作()
- 操作系统|[译]从内部了解现代浏览器(1)
- 数据库总结语句
- py连接mysql
- 2019-01-18Mysql中主机名的问题
- JS常见数组操作补充
- MySql数据库备份与恢复
- 7、前端--jQuery简介、基本选择器、基本筛选器、属性选择器、表单选择器、筛选器方法、节点操作、绑定事件