博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
python3操作mysql数据库增删改查
阅读量:3556 次
发布时间:2019-05-20

本文共 1255 字,大约阅读时间需要 4 分钟。

python3.x 使用pymysql操作mysql,python2.x使用mysqldb操作mysql

#!/usr/bin/python3import pymysqlimport typesdb=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=InnoDB  DEFAULT 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=1sql="update user set age=100 where id='%s'" % (id)try:	cursor.execute(sql)	db.commit()except:	db.rollback()	#删除id=2sql="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))

执行结果

[root@mail pythonCode]# python3 test.pyname=test1,age=1name=test3,age=3name=test4,age=4name=test5,age=5name=test6,age=6

转载地址:http://mhdrj.baihongyu.com/

你可能感兴趣的文章
Presto的概念和安装使用
查看>>
Druid的Web页面使用
查看>>
Scala-HelloWorld
查看>>
Scala-IDEA中环境部署
查看>>
Scala-HelloWorld解析
查看>>
Scala-变量和数据类型
查看>>
Scala-流程控制
查看>>
Scala-面向对象后章
查看>>
iOS蓝牙原生封装,助力智能硬件开发
查看>>
iOS 代码的Taste(品位)
查看>>
iOS开发代码规范
查看>>
iOS组件化实践(基于CocoaPods)
查看>>
【iOS学习】RxSwift从零入手 - 介绍
查看>>
数据结构之栈
查看>>
Elastic Stack简介
查看>>
关于deepin系统安装design compiler的问题解答
查看>>
Java Agent简介及使用Byte Buddy和AspectJ LTW监控方法执行耗时
查看>>
记录一下最近的学习经历
查看>>
hadoop3.0+spark2.0两台云服务器集群环境配置。
查看>>
网站实现qq登录(springboot后台)
查看>>