本博客为使用python连接mysql数据库,对其主要方法进行解析
pymysql主要使用cursor对数据库进行交互操作和结果处理,所以cursor对象为重中之重
0、一个简单的数据库交互案例
环境安装:pymysql
pip3 install pymysql
本文测试数据库结构:
create table TEST_TABLE
(
ID int auto_increment
primary key,
USER_NAME varchar(255) null,
USER_PASSWORD varchar(255) null
);
新建一个.py文件,进行一次数据库交互
# 导入package
import pymysql
# 建立数据库连接,可传参数(详见1.2)
db = pymysql.connect(host="localhost", user="root", password="123456", db="Test", charset='utf8mb4')
# 使用 cursor() 方法创建一个游标对象 cursor,可传参数,表示返回到python的结果用什么方式存储(详见2.2)
cursor = db.cursor()
# 使用List作为参数进行查询,塞入参数
params = ['Jack Ma', '123123']
# 使用 execute() 方法执行 SQL 查询,会返回受影响的行数(详见3 - 4)
cursor.execute("select * from TEST_TABLE where USER_NAME = %s and USER_PASSWORD = %s",params)
# 获取结果(详见5)
results = cursor.fetchall()
for result in results:
print("ID: %s, USER_NAME:%s, USER_PASSWORD:%s",result[0],result[1],result[2])
db.close()
可以看到,使用pymysql与数据库交互非常简单,大体分为四步:
- 建立数据库连接:
db = pymysql.connect(host="localhost", user="root", password="123456", db="Test", charset='utf8mb4')
- 获取游标对象:
cursor = db.cursor()
- 调用游标的
cursor.execute()
方法执行SQL语句 - 通过各种
cursor.fetch()
操作拿到结果集
以下为各个步骤的关键函数的详细解析
1、pymysql.connect()
创建一个数据库连接
1.1、使用案例
# 可在值前指定传入哪个参数
db = pymysql.connect(host = "localhost", user = "root", password = "123456", db = "Test",charset='utf8')
1.2、可选参数
源码注释
class Connection(object):
"""
Representation of a socket with a mysql server.
The proper way to get an instance of this class is to call
connect().
Establish a connection to the MySQL database. Accepts several
arguments:
:param host: Host where the database server is located
:param user: Username to log in as
:param password: Password to use.
:param database: Database to use, None to not use a particular one.
:param port: MySQL port to use, default is usually OK. (default: 3306)
:param bind_address: When the client has multiple network interfaces, specify
the interface from which to connect to the host. Argument can be
a hostname or an IP address.
:param unix_socket: Optionally, you can use a unix socket rather than TCP/IP.
:param read_timeout: The timeout for reading from the connection in seconds (default: None - no timeout)
:param write_timeout: The timeout for writing to the connection in seconds (default: None - no timeout)
:param charset: Charset you