Python 连接 mysql 详解(mysql-connector-python)

1 概述

1.1 第三方库:mysql-connector-python

pip install mysql-connector-python

1.2 可视化工具:navicat

在这里插入图片描述

1.3 创建测试数据库

在这里插入图片描述

-- 创建数据库
create database python_demo DEFAULT CHARSET utf8 COLLATE utf8_general_ci;

-- 创建测试表
create table python_demo.student(
  sno      int unsigned auto_increment comment '学号',
	sname    varchar(30) not null comment '姓名',
	age      int comment '年龄',
	birthday date comment '出生日期',
  primary key(sno)
) engine=innodb default charset=utf8 comment '学生信息表';

2 连接 mysql 数据库

2.1 创建一个连接

import mysql.connector

# 配置连接信息
conn = mysql.connector.connect(
    host='127.0.0.1',
    port='3306',
    user='root',
    password='12345',
    database='python_demo'
)
# 当前 mysql 版本号
print(conn.get_server_version())

2.2 捕获连接异常

import mysql.connector
from mysql.connector import errorcode

try:
    # 配置连接信息
    conn = mysql.connector.connect(
        host='127.0.0.1',
        port='3306',
        user='root',
        password='12345',
        database='python_demo'
    )
    # 当前 mysql 版本号
    print(conn.get_server_version())

    # 捕获异常
except mysql.connector.Error as err:
    if err.errno == errorcode.ER_ACCESS_DENIED_ERROR:
        print('账号或密码错误!')
    elif err.errno == errorcode.ER_BAD_DB_ERROR:
        print('数据库不存在!')
    else:
        print(err)
else:
    # 关闭连接
    conn.close()

2.3 从配置文件中获取连接信息

目录结构:
在这里插入图片描述

config.ini:

[mysql]
host = 127.0.0.1
port = 3306
user = root
password = 12345
database = python_demo

m1.py:

import mysql.connector
from mysql.connector import errorcode
import configparser

# 创建配置解析器对象
config = configparser.ConfigParser()
# 读取配置文件
config.read('config.ini')

try:
    # 配置连接信息
    conn = mysql.connector.connect(
        host=config.get('mysql', 'host'),
        port=config.get('mysql', 'port'),
        user=config.get('mysql', 'user'),
        password=config.get('mysql', 'password'),
        database=config.get('mysql', 'database')
    )
    # 当前 mysql 版本号
    print(conn.get_server_version())

    # 捕获异常
except mysql.connector.Error as err:
    if err.errno == errorcode.ER_ACCESS_DENIED_ERROR:
        print('账号或密码错误!')
    elif err.errno == errorcode.ER_BAD_DB_ERROR:
        print('数据库不存在!')
    else:
        print(err)
else:
    # 关闭连接
    conn.close()

3 执行 sql 语句

3.1 插入、更新、删除

  • execute():用来执行 sql 语句,如:增删改查,存储过程等
  • commit():用来提交事务
import mysql.connector

# 配置连接信息
conn = mysql.connector.connect(
    host='127.0.0.1',
    port='3306',
    user='root',
    password='12345',
    database='python_demo'
)

# 创建游标对象
cursor = conn.cursor()

# 操作数据:插入、修改、删除 同理,注:数据类型均可用 %s
# 操作一条数据
sql = 'insert into student(sname, age, birthday) values(%s, %s, %s);'
param = ('张三', '18', '1994-12-08')
cursor.execute(sql, param)

# 操作多条数据
sql = 'insert into student(sname, age, birthday) values(%s, %s, %s);'
param = [('李四', '20', '1992-10-05'),
         ('王五', '16', '1996-05-26'),
         ('赵六', '08', '1994-05-26')]
cursor.executemany(sql, param)

# 提交数据
conn.commit()

# 关闭游标和数据库连接
cursor.close()
conn.close()

3.2 查询

import mysql.connector

# 配置连接信息
conn = mysql.connector.connect(
    host='127.0.0.1',
    port='3306',
    user='root',
    password='12345',
    database='python_demo'
)

# 创建游标对象
cursor = conn.cursor()

# 查询数据
sql = 'select sno, sname, age, birthday from student where sno >= %s'
param = (1,)

cursor.execute(sql, param)
result = cursor.fetchall()

# 打印结果
for row in result:
    print(row)

# 关闭游标和数据库连接
cursor.close()
conn.close()

相关推荐

  1. python连接mysql数据库、FastAPI、mysql-connector-python

    2024-02-06 03:28:01       7 阅读
  2. python连接Mysql数据库

    2024-02-06 03:28:01       12 阅读
  3. python连接mysql数据库步骤

    2024-02-06 03:28:01       19 阅读
  4. python字典包连接mysql

    2024-02-06 03:28:01       9 阅读

最近更新

  1. TCP协议是安全的吗?

    2024-02-06 03:28:01       18 阅读
  2. 阿里云服务器执行yum,一直下载docker-ce-stable失败

    2024-02-06 03:28:01       19 阅读
  3. 【Python教程】压缩PDF文件大小

    2024-02-06 03:28:01       19 阅读
  4. 通过文章id递归查询所有评论(xml)

    2024-02-06 03:28:01       20 阅读

热门阅读

  1. 【Django-ninja】使用schema

    2024-02-06 03:28:01       32 阅读
  2. docker容器stop流程

    2024-02-06 03:28:01       30 阅读
  3. Linux cp命令(cp指令)解析

    2024-02-06 03:28:01       32 阅读
  4. 每日一题 力扣1696跳跃游戏

    2024-02-06 03:28:01       39 阅读
  5. 【数学1】基础数学问题

    2024-02-06 03:28:01       39 阅读
  6. 【Android】代码混淆简单介绍

    2024-02-06 03:28:01       40 阅读
  7. 异或加密原理及简单应用(C语言版)

    2024-02-06 03:28:01       37 阅读
  8. Docker Compose下载

    2024-02-06 03:28:01       34 阅读
  9. 【lesson12】高并发内存池项目最终完整版代码

    2024-02-06 03:28:01       28 阅读
  10. Simulink仿真中Simulink.ConfigSet用法

    2024-02-06 03:28:01       35 阅读
  11. 流量控制原理

    2024-02-06 03:28:01       38 阅读
  12. Android~集成opencv问题

    2024-02-06 03:28:01       33 阅读
  13. 蓝桥杯刷题day05——2023

    2024-02-06 03:28:01       33 阅读
  14. 【C语言】语句细节理解 超详细 易懂简单

    2024-02-06 03:28:01       33 阅读