python使用pymysql连接mysql并进行数据库交互详细教程(附带详细案例及解析)

本博客为使用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与数据库交互非常简单,大体分为四步:

  1. 建立数据库连接:db = pymysql.connect(host="localhost", user="root", password="123456", db="Test", charset='utf8mb4')
  2. 获取游标对象:cursor = db.cursor()
  3. 调用游标的cursor.execute()方法执行SQL语句
  4. 通过各种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 
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值