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() 
     
  • 相关阅读:
    PHP按权重随机
    PHP将汉字转为拼音
    php支持解密的加密算法示例
    小波变换检测信号突变点的MATLAB实现
    OFDM通信系统的MATLAB仿真(2)
    OFDM通信系统的MATLAB仿真(1)
    java.lang.reflect.Constructor.getParameterTypes()方法示例
    createQuery 与 createNativeQuery 区别
    java.lang.StringBuilder.deleteCharAt()方法实例
    String.format()详细用法
  • 原文地址:https://www.cnblogs.com/wdyaoyao/p/10820426.html
Copyright © 2011-2022 走看看