Python数据库编程之pymysql详解

作者:我爱让机器学习 时间:2024-01-20 03:16:19 

Python数据库编程之pymysql

学习之前务必安装MySQL并已启动相关服务。

一、pymsql的安装

在python3的环境中直接使用以下命令即可:

pip install pymysql
#或者
pip3 install pymysql

安装完毕后可使用以下命令查看:

pip list | grep PyMySQL
#注意大小写

结果如下:

Python数据库编程之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

Python数据库编程之pymysql详解

连接完数据库后,需要创建一个游标对象,模块会通过游标对象来执行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

标签:Python,Pymysql
0
投稿

猜你喜欢

  • 利用ASP远程注册DLL的方法

    2008-03-05 13:00:00
  • graphql---go http请求使用详解

    2024-02-07 08:11:56
  • 记一次vue-webpack项目优化实践详解

    2023-07-02 16:37:22
  • mysql中explain用法详解

    2024-01-13 16:28:25
  • Apache部署Django项目图文详解

    2023-12-17 06:51:05
  • SQL Server简单实现数据的日报和月报功能

    2024-01-18 15:19:17
  • Python input输入超时选择默认值自动跳过问题

    2023-02-22 07:22:40
  • PHP中$GLOBALS['HTTP_RAW_POST_DATA']和$_POST的区别分析

    2023-11-22 22:00:16
  • discuz 跨域整合的记录文件

    2023-07-23 14:17:27
  • Python箱型图绘制与特征值获取过程解析

    2023-09-20 06:22:37
  • 如何恢复/修复MS SQL数据库的MDF文件

    2007-10-30 13:52:00
  • 详解MySQL 8.0 之不可见索引

    2024-01-22 17:41:46
  • OpenCV-Python实现腐蚀与膨胀的实例

    2023-06-05 18:07:07
  • IN&EXISTS与NOT IN&NOT EXISTS 的优化原则小结

    2024-01-16 15:31:59
  • 详解在Python中处理异常的教程

    2023-08-30 15:36:26
  • 检测远程文件是否存在

    2009-06-22 13:00:00
  • 详解python中__name__的意义以及作用

    2021-11-20 19:44:24
  • python二叉树常用算法总结

    2023-01-15 01:35:18
  • 使用babel-plugin-import 实现自动按需引入方式

    2024-04-27 16:00:42
  • Windows下用py2exe将Python程序打包成exe程序的教程

    2021-07-11 23:03:17
  • asp之家 网络编程 m.aspxhome.com