zoukankan      html  css  js  c++  java
  • Python模块之PyMySQL

    PyMySQL

      介绍:

      Python中用于连接MySQL数据库的一种第三方工具库。

      安装:

      通过命令pip install pymysql安装,在Python3中可以通过pip3来安装。

      连接MySQL数据库:

      连接之前的准备工作:

        1,要有一个MySQL数据库,并且已经启动;

        2,你要知道数据库的地址,用户名和密码;

        3,你的主机拥有操作目标数据库的权限。

      基本地连接使用:

    # 导入PyMySQL模块
    import pymysql
    
    # 连接database
    conn = pymysql.connect(host="你的数据库地址", user="用户名", 
    password="密码", database="数据库名", charset="utf8")   # charset="utf8" 不能写作utf-8
    
    # 得到一个可以执行SQL语句的对象
    cursor = conn.cursor()  # 添加参数cursor=pymysql.cursors.DictCursor,可以设定执行SQL语句的返回为字典格式
    
    # 定义要执行的SQL语句
    sql = """
    CREATE TABLE USER1 (
    id INT auto_increment PRIMARY KEY ,
    name CHAR(10) NOT NULL UNIQUE,
    age TINYINT NOT NULL
    )ENGINE=innodb DEFAULT CHARSET=utf8;
    """
    # 执行SQL语句
    cursor.execute(sql)
    
    # 关闭光标对象
    cursor.close()
    
    # 关闭数据库连接
    conn.close()

      增删改查:

        基本格式

    import pymysql
    
    conn = pymysql.connect(host="你的数据库地址", user="用户名", 
    password="密码", database="数据库名", charset="utf8")
    
    cursor = conn.cursor()
    
    sql = "Mysql增删改查语句"
    
    cursor.execute(sql)
    
    conn.commit()  # 增删改需要提交事务
    cursor.close()
    conn.close()

        如果要动态操作数据,可以在SQL语句中使用%s格式化输出。例如:

    sql = "INSERT INTO USER1(name, age) VALUES (%s, %s);"
    username = "tom"
    age = 18
    cursor.execute(sql, [username, age])

         如果要获取新添加的数据的ID,可以在提交事务后通过lastrowid来实现。

    cursor.execute(sql)
    conn.commit()
    # 提交之后,获取最后一条数据的ID
    last_id = cursor.lastrowid

        查询结果获取

          1,获取单条数据

    # 执行SQL语句
    cursor.execute(sql)
    # 获取单条查询数据
    ret = cursor.fetchone()

          2,获取多条数据

    # 执行SQL语句
    cursor.execute(sql)
    # 获取全部查询数据
    ret = cursor.fetchall()
    
    # 还可以获取指定数量的数据
    ret = cursor.fetchmany(3)

        批量执行

    sql = "INSERT INTO USER1(name, age) VALUES (%s, %s);"
    
    date = [(tom, 18), (jerry, 18)]
    
    cursor.executemany(sql, data)

      操作失败回滚:通过异常处理来完成。

    try:
        # 执行SQL语句
        cursor.execute(sql)
        # 提交事务
        conn.commit()
    except Exception:
        # 有异常,回滚事务
        conn.rollback()
  • 相关阅读:
    Benelux Algorithm Programming Contest 2016 Preliminary K. Translators’ Dinner(思路)
    Benelux Algorithm Programming Contest 2016 Preliminary Target Practice
    Benelux Algorithm Programming Contest 2016 Preliminary I. Rock Band
    Benelux Algorithm Programming Contest 2016 Preliminary A. Block Game
    ICPC Northeastern European Regional Contest 2019 Apprentice Learning Trajectory
    ICPC Northeastern European Regional Contest 2019 Key Storage
    2018 ACM ICPC Asia Regional
    2018 ACM ICPC Asia Regional
    Mybatis入库出现异常后,如何捕捉异常
    优雅停止 SpringBoot 服务,拒绝 kill -9 暴力停止
  • 原文地址:https://www.cnblogs.com/zxc-Weblog/p/8722948.html
Copyright © 2011-2022 走看看