zoukankan      html  css  js  c++  java
  • MySQL与Python的交互

    驱动模块

    • MySQL Connentor是MySQL的官方驱动模块,对MySQL 8.0以上的兼容性比较好
    • 选择对应的Python版本直接安装即可

    创建连接

    import mysql.connector
    con = mysql.connector.connect(
        host="localhost"
        ,port="3306",
        user="root",
        password="123456",
        database="demo"
    )
    con.close()
    

    游标

    • MySQL Connector里面的游标用来执行SQL语句,而且查询返回的结果集会保存在游标中
    cursor = con.cursor()
    cursor.execute(sql语句)
    
    例如:
    cursor = con.cursor()
    sql = "SELECT * FROM table"
    cursor.execute(sql)
    for one in cursor:
        print(one[0],one[1],......)
    

    fetchone()用法

    • fetchone() 返回一条记录,如果没有记录,返回None
    • 多次使用fetchone(),会依次取得下一条结果
    cursor.execute(sql)
    print(cursor.fetchone()[0])
    

    fetchall()用法

    • fetchall() 返回所有结果,如果没有,返回None
    • fetchall() 返回的结果是二维元组
    cursor=execute(sql)
    result = cursor.fetchall()
    for index in range(len(result)):
        print(result[index])
    

    循环执行SQL语句

    • 游标对象中的executemany()可以反复执行一条SQL语句
    cursor.executemany(sql)
    

    事务控制

    con.start_transaction([事务隔离级别])
    con.commit()
    con.rollback()
    

    数据库连接池

    • 数据库连接池预先创建出一些数据库连接,然后缓存起来,避免了程序语言反复创建呵销毁连接
    • 在并发执行的应用程序中,数据库连接池显得尤为重要
    config = {......}
    pool = mysql.connector.pooling.MySQLConnectionPool(
        **config,
        pool_size=10
    )
    con=pool.get_connection()
    

    SQL预编译机制

    • 预编译SQL就是数据库提前把SQL语句编译成二进制,这样反复执行该语句的效率就会提升
    • SQL语句预编译的过程中,关键字已经被解析了,所以传入的参数都会被当做字符串处理,这样能够抵御SQL注入攻击
    username="1 OR 1=1"
    password="1 OR 1=1"
    sql="SELECT COUNT(*) FROM user WHERE username=%s AND password=%s"
    cursor.execute(sql,(username,password)) #传入的参数是元组
    print(cursor.fetchone()[0])
    

    异常处理

    • 数据库连接出错,或者语句执行错误,能够及时回滚和关闭连接
    try:
        con = mysql.connector.connect(......)
        [ con = con.start_transaction() ]
        ......
        [ con.commit ]
    except Exception as e:
        [ if "con" in dir():
             con.rollback() ]
        print(e)
    finally:
        if "con" in dir():
            con.close()
    

    数据库连接池和异常处理结合使用

    import mysql.connector.pooling
    config = {
        "host":"localhost",
        "port":3306,
        "user":"root",
        "password":"123456",
        "database":"demo"
    }
    try:
        pool = mysql.connector.pooling.MySQLConnectionPool(
            **config,
            pool_size=10
        )
        con=pool.get_connection()
        con.start_transaction()
        cursor = con.cursor()
        sql = "......"
        cursor.execute(sql)
        con.commit()
    except Exception as e:
        if "con" in dir():
            con.rollback()
    finally:
        if "con" in dir():
            con.close()
    
  • 相关阅读:
    【BZOJ4637】期望 Kruskal+矩阵树定理
    IEnumerable是什么
    (转)IIS windows认证
    使用pgrouting进行最短路径搜索
    Nginx设置防止IP及非配置域名访问
    java 调用c# web api 代码
    一台机器部署多个tomcat服务 nginx反向代理多个服务 笔记
    利用Kettle 从Excel中抽取数据写入SQLite
    sql server 统计信息
    sql server 索引碎片相关问题
  • 原文地址:https://www.cnblogs.com/felixqiang/p/11075061.html
Copyright © 2011-2022 走看看