Python数据库编程之pymysql详解
作者:我爱让机器学习 时间:2024-01-20 03:16:19
Python数据库编程之pymysql
学习之前务必安装MySQL并已启动相关服务。
一、pymsql的安装
在python3的环境中直接使用以下命令即可:
pip install pymysql
#或者
pip3 install pymysql
安装完毕后可使用以下命令查看:
pip list | grep PyMySQL
#注意大小写
结果如下:
二、连接数据库
pymysql连接数据库使用的是 pymsql.connect() 函数,其常用参数如下:
参数 | 说明 |
---|---|
dsn | 数据源名称,给出该参数表示数据库依赖 |
host=None | 数据库连接地址 |
user=None | 数据库用户名 |
password=‘’ | 数据库用户密码 |
database=None | 要连接的数据库名称 |
port=3306 | 端口号,默认为3306 |
charset=‘’ | 要连接的数据库的字符编码(可以在终端登陆mysql后使用 \s 查看,如下图) |
connect_timeout=10 | 连接数据库的超时时间,默认为10 |
port=3306 | 端口号,默认为3306 |
连接完数据库后,需要创建一个游标对象,模块会通过游标对象来执行sql语句以及获取查询结果,接下来直接通过代码展示各方法。
示例:
import pymysql
db = pymysql.connect(
host="localhost",
port=3306,
user='root', #在这里输入用户名
password='888888', #在这里输入密码
charset='utf8mb4'
) #连接数据库
cursor = db.cursor() #创建游标对象
sql = 'show databases' #sql语句
cursor.execute(sql) #执行sql语句
one = cursor.fetchone() #获取一条数据
print('one:',one)
many = cursor.fetchmany(3) #获取指定条数的数据,不写默认为1
print('many:',many)
all = cursor.fetchall() #获取全部数据
print('all:',all)
cursor.close()
db.close() #关闭数据库的连接
运行结果:
one: ('coldbox',)
many: (('coldboxtest',), ('db_student',), ('information_schema',))
all: (('mysql',), ('performance_schema',), ('sys',), ('test',), ('wan',))
从结果可以看出,fetchone(),fetchmany(size),fetchall() 三个函数返回值都是元组,但是fetchone()返回的是单个元组,另外两个返回的都是元组的嵌套。
三、创建和管理数据库
使用游标对象来执行创建和删除数据库的sql语句示例:
import pymysql
db = pymysql.connect(
host="localhost",
port=3306,
user='root', #在这里输入用户名
password='888888', #在这里输入密码
charset='utf8mb4'
)
cursor = db.cursor() #创建游标对象
try:
sql = 'show databases'
cursor.execute(sql)
print('未创建数据库前:',cursor.fetchall()) #获取创建数据库前全部数据库
dbname = 'justtest'
sql = 'create database if not exists %s'%(dbname) #创建数据库
cursor.execute(sql)
sql = 'show databases'
cursor.execute(sql)
print('创建新的数据库后:',cursor.fetchall()) #获取创建数据库后全部数据库
sql = 'drop database if exists %s'%(dbname) #删除数据库
cursor.execute(sql)
sql = 'show databases'
cursor.execute(sql)
print('删除新的数据库后:',cursor.fetchall()) #获取删除数据库后全部数据库
except Exception as e:
print(e)
db.rollback() #回滚事务
finally:
cursor.close()
db.close() #关闭数据库连接
运行结果:
未创建数据库前: (('coldbox',), ('coldboxtest',), ('db_student',), ('information_schema',), ('mysql',), ('performance_schema',), ('sys',), ('test',), ('wan',))
创建新的数据库后: (('coldbox',), ('coldboxtest',), ('db_student',), ('information_schema',), ('justtest',), ('mysql',), ('performance_schema',), ('sys',), ('test',), ('wan',))
删除新的数据库后: (('coldbox',), ('coldboxtest',), ('db_student',), ('information_schema',), ('mysql',), ('performance_schema',), ('sys',), ('test',), ('wan',))
四、创建和管理表
使用游标对象来执行创建和管理表的sql语句示例:
import pymysql
db = pymysql.connect(
host="localhost",
port=3306,
user='root', #在这里输入用户名
password='888888', #在这里输入密码
charset='utf8mb4',
database='justtest' #指定操作的数据库
)
cursor = db.cursor() #创建游标对象
try:
tableName = 'user'
sql = 'create table %s (id varchar(20) not null, name varchar(20) not null, primary key(id))'%(tableName)
cursor.execute(sql) #执行sql语句,创建表
sql = 'show tables'
cursor.execute(sql)
print('显示创建的表:',cursor.fetchall()) #显示创建的表
sql = 'desc %s'%(tableName)
cursor.execute(sql)
print('显示表结构:',cursor.fetchall()) #显示表结构
except Exception as e:
print(e)
db.rollback() #回滚事务
finally:
cursor.close()
db.close() #关闭数据库连接
运行结果:
显示创建的表: (('user',),)
显示表结构: (('id', 'varchar(20)', 'NO', 'PRI', None, ''), ('name', 'varchar(20)', 'NO', '', None, ''))
方法名 | 说明 |
---|---|
callproc(procname,[,parameters]) | 调用存储过程,需要数据库支持 |
close() | 关闭当前游标 |
execute(operation,[,parameters]) | 执行数据库操作,sql语句或者数据库命令 |
executemany(operation, seq_of_params) | 用于批量操作 |
fetchone() | 获取查询结果集合中的下一条记录 |
fetchmany(size) | 获取指定数量的记录 |
fetchall() | 获取查询结果集合所有记录 |
nextset() | 跳至下一个可用的数据集 |
arraysize | 指定使用fetchmany()获取的行数,默认为1 |
setinputsizes(size) | 设置调用execute*()方法时分配的内存区域大小 |
setoutputsizes(size) | 设置列缓冲区大小,对大数据列尤其有用 |
来源:https://blog.csdn.net/youngwyj/article/details/124699636
![](/images/zang.png)
![](/images/jiucuo.png)
猜你喜欢
利用ASP远程注册DLL的方法
graphql---go http请求使用详解
记一次vue-webpack项目优化实践详解
![](https://img.aspxhome.com/file/2023/0/139740_0s.jpg)
mysql中explain用法详解
Apache部署Django项目图文详解
![](https://img.aspxhome.com/file/2023/2/134802_0s.png)
SQL Server简单实现数据的日报和月报功能
Python input输入超时选择默认值自动跳过问题
![](https://img.aspxhome.com/file/2023/5/112995_0s.png)
PHP中$GLOBALS['HTTP_RAW_POST_DATA']和$_POST的区别分析
discuz 跨域整合的记录文件
Python箱型图绘制与特征值获取过程解析
![](https://img.aspxhome.com/file/2023/6/124246_0s.png)
如何恢复/修复MS SQL数据库的MDF文件
详解MySQL 8.0 之不可见索引
OpenCV-Python实现腐蚀与膨胀的实例
![](https://img.aspxhome.com/file/2023/9/117619_0s.png)
IN&EXISTS与NOT IN&NOT EXISTS 的优化原则小结
详解在Python中处理异常的教程
检测远程文件是否存在
详解python中__name__的意义以及作用
python二叉树常用算法总结
使用babel-plugin-import 实现自动按需引入方式
![](https://img.aspxhome.com/file/2023/2/133052_0s.jpg)