Python - Python连接数据库

发布于:2025-02-27 ⋅ 阅读:(106) ⋅ 点赞:(0)

Python的标准数据库接口为:Python DB-API,Python DB-API为开发人员提供了数据库应用编程接口。

PyMySQL 是在 Python3.x 版本中用于连接 MySQL 服务器的一个实现库,Python2中则使用mysqldb。 PyMySQL 遵循 Python 数据库 API v2.0 规范,并包含了 pure-Python MySQL 客户端库。

一、安装PyMySQL

在使用 PyMySQL 之前,我们需要确保 PyMySQL 已安装。

PyMySQL 下载地址:https://github.com/PyMySQL/PyMySQL

如果还未安装,我们可以使用以下命令安装最新版的 PyMySQL:

pip install PyMySQL

二、连接数据库

1、建表

数据库准备,连接数据库之前,请确保已经创建了python数据库,以及students表

建表SQL如下:

CREATE TABLE `student`  (
  `id` int NOT NULL AUTO_INCREMENT COMMENT '主键',
  `stu_name` varchar(20) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci NULL DEFAULT NULL COMMENT '学生名字',
  `stu_class` varchar(50) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci NULL DEFAULT NULL COMMENT '学生班级',
  `stu_age` int NULL DEFAULT NULL COMMENT '学生年龄',
  PRIMARY KEY (`id`) USING BTREE
) ENGINE = InnoDB AUTO_INCREMENT = 4 CHARACTER SET = utf8mb4 COLLATE = utf8mb4_unicode_ci COMMENT = '学生表' ROW_FORMAT = Dynamic;

2、创建Connection 对象:用于建立与数据库的连接

from pymysql import * 
# 导入pymysql模块 
# 创建连接对象 Connection对象 
# host:数据库主机地址 
# user:数据库账号 
# password:数据库密码 
# database : 需要连接的数据库的名称 
# port: mysql的端口号 
# charset: 通信采用编码格式 
conn = connect(host='127.0.0.1', user='root', password='mysql', database='python', port=3306, charset='utf8') 

1、Connection 连接对象拥有的方法

close():关闭连接,连接数据库跟打开文件一样,操作完成之后需要关闭,否则会占用连接

commit():提交,pymysql 默认开启事物,所以每次更新数据库都要提交 rollback()回滚,事务回滚

cursor():返回Cursor对象,用于执行sql语句并获得结果

2、获取cursor对象

cur = conn.cursor() # cursor对象用于执行sql语句 

3、cursor对象拥有的方法

close():关闭cursor对象

execute(operation [, parameters ]) 执行语句,返回受影响的行数,可以执行所有语句

fetchone():获取查询结果集的第一个行数据,返回一个元组

fetchall():执行查询时,获取结果集的所有行,一行构成一个元组,再将这些元组装入一个元组返回

3、SQL增删改查

1、插入语句

insertSql = '''insert into student(stu_name,stu_class,stu_age) values ('张三','高三一班',18)'''
cur.execute(insertSql)
conn.commit()  # 提交事务

2、查询语句

cur.execute('select * from students;') # 执行sql语句,select * from students; 
res = cur.fetchone() # 获取结果集的第一条数据 
res1 = cur.fetchall() # 获取结果及的所有数据 
print(res) # 将获取的查询结果打印 
print(res1) 

3、占位符:%s

执行sql语句参数化,参数化sql语句中使用%s占位。 execute(operation [parameters]) 执行语句,返回受影响的行数,可以执行所有语句 [parameters] 参数列表

# sql语句中使用%s占位
sql = 'select * from students where id=%s and stu_name= %s;' 	
# 执行sql语句
cur.execute(sql, [1,'张三'])
from pymysql import *

'''
创建Connection 对象:用于建立与数据库的连接
导入pymysql模块 
# 创建连接对象 Connection对象 
# host:数据库主机地址 
# user:数据库账号 
# password:数据库密码 
# database : 需要连接的数据库的名称 
# port: mysql的端口号 
# charset: 通信采用编码格式
'''
conn = connect(host='localhost', port=3306, user='root', password='mysql', database='my_db', charset='utf8')

try:
    # 创建游标对象
    cur = conn.cursor()
    # 执行sql语句
    # insertSql = '''insert into student(stu_name,stu_class,stu_age) values ('张三','高三一班',18);'''
    # cur.execute(insertSql)
    # conn.commit()  # 提交事务
    selectSql = '''select * from student where id=%s;'''
    cur.execute(selectSql,3)
    # selectSql = '''select * from student;'''
    # cur.execute(selectSql)
    # res = cur.fetchone()  # 获取结果集的第一条数据
    # print(res)
    # 获取结果及的所有数据
    result = cur.fetchall()
    for item in result:
        # 姓名:张三,班级:高三一班,年龄:18
        print('姓名:{0},班级:{1},年龄:{2}'.format(item[1], item[2], item[3]))
except Exception as msg:
    print(msg.args)
finally:
    # 关闭游标对象
    cur.close()
    # 关闭连接对象
    conn.close()

三、封装连接PyMySQL数据库工具

创建一个db_client.py文件

import pymysql

class DBUtil():
    conn=None
    @classmethod
    def get_conn(cls):
        if cls.conn is None:
            cls.conn=pymysql.connect(host="localhost",port=3306,user="root",password="mysql",database="my_db",charset="utf8")
        return cls.conn

    @classmethod
    def close_conn(cls):
        if cls.conn is not None:
            cls.conn.close()
            cls.conn=None

    @classmethod
    def select_all(cls,sql):
        cursor=None
        result=None
        try:
            cls.get_conn()
            cursor=cls.conn.cursor()
            cursor.execute(sql)
            result=cursor.fetchall()
        except Exception as e:
            print(e)
        finally:
            cursor.close()
            cls.close_conn()
            return result

    @classmethod
    def uid(cls,sql):
        cursor=None
        try:
            cls.get_conn()
            cursor=cls.conn.cursor()
            cursor.execute(sql)
            cls.conn.commit()
        except Exception as e:
            print(e)
            cls.conn.rollback()
        finally:
            cursor.close()
            cls.close_conn()
print('--------数据库工具DB--------')
# ((3, '张三', '高三一班', 18), (4, '李四', '高三二班', 16))
print(DBUtil.select_all("select * from student"))