Python实现MySQL数据库连接—pymysql

导入模块

import json
import pymysql
import time
import traceback

读取JSON文件,并将其转换为Python数据格式–字典

fo = open('./DouBanTOP250_info_primary.txt', 'r')
info = json.load(fo)
fo.close()

连接数据库管理系统

conn = pymysql.connect(
    user = 'YourUserName',
    password = 'YourPassword',
    # MySQL的默认端口为3306
    port = 3306,
    # 本机地址为127.0.0.1或localhost
    host = '127.0.0.1',
    # 指定使用的数据库
    init_command = 'use DouBanTOP250_info'
)
# 创建游标对象
cur = conn.cursor()

init_command是在数据库连接成功后执行的SQL语句,
其中

use DouBanTOP250_info

的含义是使用数据库DouBanTOP250_info,故可以使用pymysql.connect()的database参数代替
即:

conn = pymysql.connect(
    user = 'YourUserName',
    password = 'YourPassword',
    # MySQL的默认端口为3306
    port = 3306,
    # 本机地址为127.0.0.1或localhost
    host = '127.0.0.1',
    # 指定使用的数据库
    database = 'DouBanTOP250_info'
)
# 创建游标对象
cur = conn.cursor()

上述的两种写法是等效的。

初始化操作(在指定的表不存在时,创建一张表)

# 创建表的SQL语句
SQL = 'create table if not exists info('\
      'id int primary key,' \
      'title char not null,' \
      'photo_src char not null)'
try:
    # 开启一个事务
    conn.begin()
    # 设置将执行的SQL语句
    cur.execute(SQL)
    # 提交事务
    conn.commit()
except Exception:
    print('【初始化失败(表)】')
    # 打印错误信息
    print('    ', traceback.print_exc())
    pass

traceback.print_exc(file=fo)

其中fo是一个文件对象,可以使用open()函数创建
可将错误信息输出到指定的文件(fo)中。

将数据插入到目标数据库的指定表中

start = time.time()
# 将数据插入到目标数据库的指定表中
try:
    # 开启一个事务
    conn.begin()
    for item in info.values():
        cur.execute('insert into info (title, photo_src) values(%s, %s)', [item['title'], item['photo_src']])
    # 提交事务
    conn.commit()
    # 记录处理时间
    process_time = time.time() - start
    # 打印处理时间
    print(process_time)
except Exception:
    print('【插入数据失败】')
    # 打印错误信息
    print(traceback.print_exc())
    pass
# 关闭游标
cur.close()
# 关闭连接
conn.close()

cur.execute(‘insert into info (title, photo_src) values(%s, %s)’, [item[‘title’], item[‘photo_src’]])

不要直接拼接字符串来构造需要执行的SQL语句,推荐使用参数完成构造,理由有二:

  1. 参数SQL会被系统缓存,当多次执行同一语句时,无需对SQL进行反复编译。
  2. 可防止SQL注入。

注:
短时间有大量不同的SQL语句需要循环执行时,在条件允许的情况下,应在循环结束后提交事务。
若使用下述代码(每循环一次提交一次事务):

start = time.time()
# 将数据插入到目标数据库的指定表中
try:
    # 开启一个事务
    conn.begin()
    for item in info.values():
        cur.execute('insert into info (title, photo_src) values(%s, %s)', [item['title'], item['photo_src']])
    	# 提交事务   <-------------------------改动一处
    	conn.commit() 
    # 记录处理时间
    process_time = time.time() - start
    # 打印处理时间
    print(process_time)
except Exception:
    print('【插入数据失败】')
    # 打印错误信息
    print(traceback.print_exc())
    pass
# 关闭游标
cur.close()
# 关闭连接
conn.close()

花费时间将由原来的1.5s(平均)上升到7.5s(平均),性能方面将出现很大的损失。

代码总汇

# 导入模块
import json
import pymysql
import time
import traceback


# 读取JSON文件,并将其转换为Python数据格式--字典
fo = open('./DouBanTOP250_info_primary.txt', 'r')
info = json.load(fo)
fo.close()


# 连接数据库管理系统
conn = pymysql.connect(
    user = 'YourUserName',
    password = 'YourPassword',
    # MySQL的默认端口为3306
    port = 3306,
    # 本机地址为127.0.0.1或localhost
    host = '127.0.0.1',
    # 指定使用的数据库
    init_command = 'use DouBanTOP250_info'
    # 上述语句可使用
    # database = DouBanTOP250_info
    # 进行替换
)
# 创建游标对象
cur = conn.cursor()


# 初始化操作(在指定的表不存在时,创建一张表)
# 创建表的SQL语句
SQL = 'create table if not exists info('\
      'id int primary key,' \
      'title char not null,' \
      'photo_src char not null)'
try:
    # 开启一个事务
    conn.begin()
    # 设置将执行的SQL语句
    cur.execute(SQL)
    # 提交事务
    conn.commit()
except Exception:
    print('【初始化失败(表)】')
    # 打印错误信息
    print('    ', traceback.print_exc())
    # traceback.print_exc(file=fo)
    # (其中fo是一个文件对象,可以使用open()函数创建)
    # 可将错误信息输出到指定的文件(fo)中。
    pass


# 布置计时器
start = time.time()
# 将数据插入到目标数据库的指定表中
try:
    # 开启一个事务
    conn.begin()
    for item in info.values():
        # 不要直接拼接字符串来构造需要执行的SQL语句,推荐使用参数完成构造,理由有二:
        # (cur.execute(SQL, args)
        # 1. 参数SQL会被系统缓存,当多次执行同一语句时,无需对SQL进行反复编译。
        # 2. 可防止SQL注入
        cur.execute('insert into info (title, photo_src) values(%s, %s)', [item['title'], item['photo_src']])
    # 提交事务
    conn.commit()
    # 记录处理时间
    process_time = time.time() - start
    # 打印处理时间
    print(process_time)
except Exception:
    print('【插入数据失败】')
    # 打印错误信息
    print(traceback.print_exc())
    pass
# 关闭游标
cur.close()
# 关闭连接
conn.close()

共计人评分,平均

到目前为止还没有投票!成为第一位评论此文章。

(0)
乘风的头像乘风管理团队
上一篇 2023年3月11日
下一篇 2023年3月11日

相关推荐