pymysql库使用介绍
- Python下操作MySql数据库的模块
- 以下所有操作皆在
python3
环境 - pymsql官方文档
安装
pip install pymysql
连接数据库
import pymysql
#创建连接,这里的charset,可以直接使用utf8,至于两者的区别,自行了解
db = pymsql.connect(host='127.0.0.1',
port=3306,
user='root',
password='123',
db='test',
charset='utf8mb4')
# 创建游标,这里的游标并不等同于MySql数据库中的游标,只是处理数据的一种方法,
# 通过游标我们可以指定结果集中的任何位置,通俗的讲,要想获取我们执行sql命令后的结果,就需要通过游标来操作
curse = db.cursor()
# 新建数据库,注意sql语句中用双引号
createDB = "create database baiduspider default character set utf8mb4;"
# 执行sql语句,execute(query, args=None),query为sql语句,如果语句中有占位符%s,则args需提供对应的值
curse.execute(createDB)
# 切换数据库
db.select_db('baiduspider')
#查看当前链接的数据库
curse.execute("select databases();")
curse.fetchone()
# 创建表
createTable = "create table if not exists baidu(id int not null,title varchar(120),href varchar(300),primary key (id))"
curse.execute(createTable)
# 查看表
curse.execute("show tables;")
curse.fetchone()
插入数据
data = {
"id":1,
'title':'baidu',
'href':'https://www.baidu.com'
}
keys = data.keys()
table = 'baidu'
insertSql = f"insert into {table} ({','.join(keys)}) value ({tuple(['%s']*len(keys))});"
try:
# 执行插入命令
curse.execute(insertSql,tuple(data.values()))
# 提交数据库事务
db.commit()
except:
# 回滚事务
db.rollback()
查询数据
table = 'baidu'
condition = 'id = 1'
selectSql = "select * from %s where %s;"
try:
curse.execute(selectSql,(table,condition))
data = curse.fetchone()
# fetchone 输出结果中的下一条数据
# fetchall 输出结果中的所有数据,如果数据量大,不建议使用
# fetchmany 指定输出多少条数据
while data:
print(data)
data = curse.fetchone()
except:
print('Error')
更新数据
# 注意,占位符只有%s,不等同于python中的%s,这里int型的占位符也是%s
updateSql = "update baidu set title = %s where id = %s;"
try:
curse.execute(updateSql,('baidu',1))
db.commit()
except:
db.rollback()
使用唯一索引插入/更新数据
data = {
'id':1,
'title':'wangyi',
'href':'https://www.163.com'
}
table = 'baidu'
keys = ','.join(data.keys())
values = tuple(data.values())
in_up_sql = f"insert into {table} ({keys}) values {values} on duplicate key update "
upsql = ','.join([f"{key}=%s" for key in data.keys()])
sql = in_up_sql + upsql
'''
完整sql语句如下:
"insert into baidu (id,title,href) values (1, 'wangyi', 'https://www.163.com') on duplicate key update id=%s,title=%s,href=%s"
首先进行插入操作,如果已存在唯一的索引,比如这里数据库中已经存在id=1的数据,则会对其进行更新
'''
try:
curse.execute(sql,values)
db.commit()
except:
db.rollback()
删除数据
table = "baidu"
condition = "id = 1"
delSql = "delete from %s where %s;"
try:
curse.execute(delSql,(table,condition))
db.commit()
except:
db.rollback()
关闭连接
curse.close()
db.close()