1.连接MySQL
MySQL
一般操作分为四步骤:
- 构造数据库对象
- 获取游标
- 执行SQL语句
- 关闭数据库
示例:
连接数据库并查询
import redis
import pymysql
def load_data_from_database():
# 从数据库中加载热门数据的逻辑
# 这里假设使用MySQL数据库,根据实际情况修改连接参数和SQL语句
connection = pymysql.connect(
host='xxxxx',
user='xxxxx',
password='xxxxx',
database='xxxx',
# charset='utf8mb4',
# cursorclass=pymysql1.cursors.DictCursor
)
try:
#创建一个游标对象 cursor
with connection.cursor() as cursor:
# 从数据库中查询热门数据
sql = 'SELECT id, name FROM users'
cursor.execute(sql)
result = cursor.fetchall()
print(result)
return result
finally:
connection.close()
load_data_from_database()
- cursor.fetchone():查询单条数据
- cursor.fetchall():查询多条数据
- rowcount: 这是一个只读属性,并返回执行execute()方法后影响的行数。
- rownumber:表示最后一次执行
fetch操作后游标的位置,即当前已经取得的行数。 - description:返回由元组组成的序列,每个元组对应于结果集的列,包含了列的描述信息,如列名、类型等。
- arraysize:用于指定在调用
fetchmany()方法时,每次获取的行数,默认为 1。 - connection:返回与游标关联的数据库连接对象。
- lastrowid:在执行插入操作后,返回最后插入的行的自增主键值。
- nextset():如果有多个结果集,用于移动到下一个结果集。
- fetchwarnings():返回最近一次执行的 SQL 语句所产生的警告信息。
创建表:
# 使用预处理语句创建表
sql = """CREATE TABLE EMPLOYEE (
FIRST_NAME CHAR(20) NOT NULL,
LAST_NAME CHAR(20),
AGE INT,
SEX CHAR(1),
INCOME FLOAT )"""
cursor.execute(sql)
插入操作:
# SQL 插入语句
sql = """INSERT INTO EMPLOYEE(FIRST_NAME,
LAST_NAME, AGE, SEX, INCOME)
VALUES ('Mac', 'Mohan', 20, 'M', 2000)"""
try:
# 执行sql语句
cursor.execute(sql)
# 提交到数据库执行
db.commit()
except:
# 如果发生错误则回滚
db.rollback()
#以下形式也行
# SQL 插入语句
sql = "INSERT INTO EMPLOYEE(FIRST_NAME, \
LAST_NAME, AGE, SEX, INCOME) \
VALUES ('%s', '%s', %s, '%s', %s)" % \
('Mac', 'Mohan', 20, 'M', 2000)
查询:
# SQL 查询语句
sql = "SELECT * FROM EMPLOYEE \
WHERE INCOME > %s" % (1000)
try:
# 执行SQL语句
cursor.execute(sql)
# 获取所有记录列表
results = cursor.fetchall()
for row in results:
fname = row[0]
lname = row[1]
age = row[2]
sex = row[3]
income = row[4]
# 打印结果
print ("fname=%s,lname=%s,age=%s,sex=%s,income=%s" % \
(fname, lname, age, sex, income ))
更新:
sql = "UPDATE EMPLOYEE SET AGE = AGE + 1 WHERE SEX = '%c'" % ('M')
# 执行SQL语句
cursor.execute(sql)
# 提交到数据库执行
db.commit()
删除:
sql = "DELETE FROM EMPLOYEE WHERE AGE > %s" % (20)
# 执行SQL语句
cursor.execute(sql)
# 提交修改
db.commit()
示例:多表联查和子查询
import pymysql
# 建立数据库连接
connection = pymysql.connect(host='localhost',
user='your_username',
password='your_password',
database='your_database',
cursorclass=pymysql.cursors.DictCursor)
try:
with connection.cursor() as cursor:
# 执行多表联查查询
sql = """
SELECT orders.order_id, orders.order_date, orders.total_amount, customers.customer_name
FROM orders
INNER JOIN customers ON orders.customer_id = customers.customer_id
WHERE customers.customer_id = %s
"""
# 指定客户的 ID
customer_id = 1 # 例如,假设要获取客户 ID 为 1 的所有订单
# 执行 SQL 查询
cursor.execute(sql, (customer_id,))
# 获取查询结果
results = cursor.fetchall()
# 打印查询结果
for row in results:
print("Order ID:", row['order_id'])
print("Order Date:", row['order_date'])
print("Total Amount:", row['total_amount'])
print("Customer Name:", row['customer_name'])
print("\n")
finally:
# 关闭数据库连接
connection.close()
传入多个参数示例:
import pymysql
# 建立数据库连接
connection = pymysql.connect(host='localhost',
user='your_username',
password='your_password',
database='your_database',
cursorclass=pymysql.cursors.DictCursor)
try:
with connection.cursor() as cursor:
# 执行 SQL 查询,使用多个参数
sql = """
SELECT *
FROM your_table
WHERE column1 = %s AND column2 = %s
"""
# 指定多个参数的值
param1 = 'value1'
param2 = 'value2'
# 执行 SQL 查询,传递多个参数
cursor.execute(sql, (param1, param2))
# 获取查询结果
results = cursor.fetchall()
# 处理查询结果...
finally:
# 关闭数据库连接
connection.close()
Reference Links:
#菜鸟教程
#Python3 MySQL 数据库连接 - PyMySQL 驱动