Python3使用PyMySQL操作MySQL

PyMySQL 是在 Python3.x 版本中用于连接 MySQL 服务器的一个库,Python2中则使用mysqldb。

PyMySQL 遵循 Python 数据库 API v2.0 规范,并包含了 pure-Python MySQL 客户端库。

1 基本介绍

1.1 安装PyMySQL

$ pip3 install PyMySQL

1.2 导入模块

import pymysql

1.3 链接数据库

# 实例1(一般连接将数据读入本地内存):
con = pymysql.connect( host='localhost', port=3306, user='root', password='passwd', database='testdb')
    
# 实例2(大数据连接):
con = pymysql.connect( host='localhost', port=3306, user='root', password='passwd', database='testdb', 
               charset='utf8', cursorclass = pymysql.cursors.SSCursor)
    
# 实例3(连接配置信息):
config = {'host' : 'localhost', 'port' : 3306, 'user' : 'root', 'password' : 'passwd', 'db' : 'testdb'}
db = pymysql.connect(**config) 

1.4 创建游标

cursor = connect.cursor()

1.5 执行SQL语句

# 示例1
sql = "insert into tableName values('%s','%d')"
cursor.excute(sql(value1,value2))
# 示例2
cursor.execute("SELECT VERSION()")

1.6 获取数据

# 获取一条数据
data1 = cursor.fetchone()         
# 获取多条数据
data2 = cursor.fetchmany()        
# 获取所有数据
data3 = cursor.fetchall()         
# 获取字段信息
fields = cursor.description       

1.7 提交并关闭

# 关闭游标
cursor.close()            
# 提交数据更改,涉及数据的更改时需要提交
connect.commit()  
# 关闭数据库连接
connect.close()           

2 脚本举例

2.1 查询

#!/usr/bin/python3
import pymysql
 
# 打开数据库连接
db = pymysql.connect(
    host='172.0.0.1',
    port=3306,
    user='root',
    password='password',
    db='testdb',
) 
 
# 使用 cursor() 方法创建一个游标对象 cursor
cursor = db.cursor()
 
# 使用 execute()  方法执行 SQL 查询 
cursor.execute("SELECT VERSION()")
 
# 使用 fetchone() 方法获取单条数据.
data = cursor.fetchone()
 
# 打印信息
print ("Database version : %s " % data)
 
# 关闭数据库连接
db.close()

2.2 插入数据

#!/usr/bin/python3

# 引入pymysql模块
import pymysql
 
# 打开数据库连接
config = {'host' : '172.0.0.1', 'port' : 3306, 'user' : 'root', 'password' : 'password', 'db' : 'xq_2345'}
db = pymysql.connect(**config) 
 
# 使用 cursor() 方法创建一个游标对象 cursor
cursor = db.cursor()

app_version = '3.4'
online_time = 1519709184
content = '版本内容'
sql = "INSERT INTO changelog (app_version, online_time, content, state)  VALUES ({}, {}, {}, 1)".format(app_version, online_time, content)

try:
  # 执行sql语句
  cursor.execute(sql)
  # 提交到数据库执行
  db.commit()
except Exception as e:
  print(e)
  # 如果发生错误则回滚
  db.rollback()
 

# 关闭数据库连接
db.close()

附: connections 模块

类:Connection
用法:执行 pymysql.connect() 得到。而不是构造函数 Connection()。
pymysql.connect() 的参数即为 Connection() 构造函数的参数。
构造函数:

pymysql.connections.Connection(self,
    host=None,          # 要连接的主机地址
    user=None,          # 用于登录的数据库用户
    password='',        # 密码
    database=None,      # 要连接的数据库
    port=0,             # 端口,一般为 3306
    unix_socket=None,   # 选择是否要用unix_socket而不是TCP/IP
    charset='',         # 字符编码
    sql_mode=None,      # Default SQL_MODE to use.
    read_default_file=None, # 从默认配置文件(my.ini或my.cnf)中读取参数
    conv=None,          # 转换字典
    use_unicode=None,   # 是否使用 unicode 编码
    client_flag=0,      # Custom flags to send to MySQL. Find potential values in constants.CLIENT.
    cursorclass=<class 'pymysql.cursors.Cursor'>, # 选择 Cursor 类型
    init_command=None,  # 连接建立时运行的初始语句 
    connect_timeout=10, # 连接超时时间,(default: 10, min: 1, max: 31536000)
    ssl=None,           # A dict of arguments similar to mysql_ssl_set()'s parameters.For now the capath and cipher arguments are not supported. 
    read_default_group=None, # Group to read from in the configuration file.
    compress=None,      # 不支持
    named_pipe=None,    # 不支持
    no_delay=None,      # 
    autocommit=False,   # 是否自动提交事务
    db=None,            # 同 database,为了兼容 MySQLdb
    passwd=None,        # 同 password,为了兼容 MySQLdb
    local_infile=False, # 是否允许载入本地文件
    max_allowed_packet=16777216, # 限制 `LOCAL DATA INFILE` 大小
    defer_connect=False, # Don't explicitly connect on contruction - wait for connect call.
    auth_plugin_map={}, #
    read_timeout=None,  # 
    write_timeout=None, 
    bind_address=None   # 当客户有多个网络接口,指定一个连接到主机
    )
发布了102 篇原创文章 · 获赞 6 · 访问量 9万+

猜你喜欢

转载自blog.csdn.net/tt75281920/article/details/104882224