zoukankan      html  css  js  c++  java
  • Connector for Python

    PyMySQL安装:

    pip install pymysql

    连接数据库:

    基本操作:

    # 导入pymysql模块
    import pymysql
    # 连接database
    conn = pymysql.connect(host=“你的数据库地址”, user=“用户名”,password=“密码”,database=“数据库名”,charset=“utf8”)
    # 1.得到一个可以执行SQL语句的光标对象
    cursor = conn.cursor()
    # 2.得到一个可以执行SQL语句并且将结果作为字典返回的游标
    cursor = conn.cursor(cursor=pymysql.cursors.DictCursor)
    # 定义要执行的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()

    增删改查操作:

    增:
    sql = "INSERT INTO USER1(name, age) VALUES (%s, %s);" username = "Alex" age = 18

    插入数据失败回滚:
    sql = "INSERT INTO USER1(name, age) VALUES (%s, %s);"
    username = "Alex"
    age = 18
    try:
        # 执行SQL语句
        cursor.execute(sql, [username, age])
        # 提交事务
        conn.commit()
    except Exception as e:
        # 有异常,回滚事务
        conn.rollback()

    获取插入数据ID:
    sql = "INSERT INTO USER1(name, age) VALUES (%s, %s);"
    username = "Alex"
    age = 18
    try:
        # 执行SQL语句
        cursor.execute(sql, [username, age])
        # 提交事务
        conn.commit()
        # 提交之后,获取刚插入的数据的ID
        last_id = cursor.lastrowid
    except Exception as e:
        # 有异常,回滚事务
        conn.rollback()

    删:
    sql = "DELETE FROM USER1 WHERE id=%s;"

    改:
    sql = "UPDATE USER1 SET age=%s WHERE name=%s;"
    username = "Alex"
    age = 80
    try:
        # 执行SQL语句
        cursor.execute(sql, [age, username])
        # 提交事务
        conn.commit()
    except Exception as e:
        # 有异常,回滚事务
        conn.rollback()

    查:
    # 查询数据的SQL语句
    sql = "SELECT id,name,age from USER1 WHERE id=1;"
    # 执行SQL语句
    cursor.execute(sql)
    # 获取单条查询数据
    ret = cursor.fetchone()
  • 相关阅读:
    为什么要把MySQL的binlog格式修改为row
    面试官:你知道大事务会带来什么问题以及如何解决么?
    TCP三次握手、四次挥手、滑动窗口、流量控制
    SpringCloud Gateway拦截器遇到的小坑汇总
    Zipkin客户端链路追踪源码解析
    Hystrix失败处理逻辑解析
    Feign自动装配原理
    SpringCloud服务调用源码解析汇总
    Zipkin架构简介
    C#+Selenium抓取百度搜索结果前100网址
  • 原文地址:https://www.cnblogs.com/bbeb/p/10669304.html
Copyright © 2011-2022 走看看