Python连接MySQL完整指南(mysql-connector-python)

文章目录

  • 1 概述
  • 1.1 第三方库:mysql-connector-python
  • 1.2 可视化工具:navicat
  • 1.3 创建测试数据库
  • 2 连接 mysql 数据库
  • 2.1 创建一个连接
  • 2.2 捕获连接异常
  • 2.3 从配置文件中获取连接信息
  • 3 执行 sql 语句
  • 3.1 插入、更新、删除
  • 3.2 查询
  • 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()
    

    作者:鱼丸丶粗面

    物联沃分享整理
    物联沃-IOTWORD物联网 » Python连接MySQL完整指南(mysql-connector-python)

    发表回复