一、插入操作
#coding:utf8 import pymysql.cursors #连接数据库 conn=pymysql.Connect( user="root", password="123456", port=3306, host="127.0.0.1", db="wxl123", charset="utf8" )
#设置字符编码以及自动提交 cursor=conn.cursor() cursor.execute('set names utf8') cursor.execute('set autocommit=1')
这是在navicat中建立的数据库wxl123中的一张表tb_user#插入操作sql="insert into tb_user(name,pwd)values('张三','123')
#执行sql并且得到结果cursor.execute(sql)#关闭游标和连接cursor.close()conn.close()运行结果:
二、删除操作
#coding:utf8 import pymysql.cursors #连接数据库 conn=pymysql.Connect( user="root", password="123456", port=3306, host="127.0.0.1", db="wxl123", charset="utf8" )
#设置字符编码以及自动提交 cursor=conn.cursor() cursor.execute('set names utf8') cursor.execute('set autocommit=1')
这是通过插入得到的三组数据的表tb_user
#删除id=1的一组数据sql='delete from tb_user where id={0}'.format(1)
执行sql并且得到结果cursor.execute(sql)#关闭游标和连接cursor.close()conn.close()三、改操作

将姓名是李四的密码改为666
四、查操作
1.fetchall()
sql="select * from tb_user" #执行sql并且得到结果 cursor.execute(sql) #选择结果为表中的所有 result=cursor. print(result)运行结果:((2, '李四', '666'), (3, '王麻子', '567'), (4, '小明', '888'))
2.fetchmany()
result=cursor.fetchmany(2)
运行结果:((2, '李四', '666'), (3, '王麻子', '567'))
result=cursor.fetchmany()
运行结果:((2, '李四', '666'),)
3.fetchone()
result=cursor.fetchone()
运行结果:(2, '李四', '666')

本文介绍使用Python和pymysql库对MySQL数据库进行增删改查(CRUD)的基本操作,包括插入、删除、更新及查询数据的具体实现。
&spm=1001.2101.3001.5002&articleId=79627666&d=1&t=3&u=e7d78495ee344238aa5cb0aa5e661d20)

被折叠的 条评论
为什么被折叠?



