python3操作mysql数据库增删改查

python3.x 使用pymysql操作mysql,python2.x使用mysqldb操作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=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=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])) #打印变量类型 <class 'str'>

	print ("name=%s,age=%s" % \
             (age, name))


执行结果

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


  • 0
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值