zoukankan      html  css  js  c++  java
  • psycopg使用

    1.使用示例

    import psycopg2
    
    # 建立数据库连接
    conn = psycopg2.connect("dbname=test user=postgres")
    
    # 开启游标操作数据库
    cur = conn.cursor()
    
    # 建表
    cur.execute("CREATE TABLE test (id serial PRIMARY KEY, num integer, data varchar);")
    
    # 传递参数给sql语句占位符,执行该sql语句(可避免sql注入)
    cur.execute("INSERT INTO test (num, data) VALUES (%s, %s)",(100, "abc'def"))
    
    # 查询sql,从查询结果获取数据
    cur.execute("SELECT * FROM test;")
    cur.fetchone()
    #(1, 100, "abc'def")
    
    # 提交
    conn.commit()
    
    # 关闭数据库连接
    cur.close()
    conn.close()
    

    2.向sql语句传递参数
    1)第一个参数sql语句,使用%s作占位符;第二个参数为元组或数组,待传递参数。

    cur.execute("""
    INSERT INTO some_table (an_int, a_date, a_string)
    VALUES (%s, %s, %s);
    """,
    (10, datetime.date(2005, 11, 18), "O'Reilly"))
    

    2)第一个参数sql语句,使用%(name)s作占位符;第二个参数为dict,待传递参数。

     cur.execute("""
    INSERT INTO some_table (an_int, a_date, another_date, a_string)
    VALUES (%(int)s, %(date)s, %(date)s, %(str)s);
    """,
    {'int': 10, 'str': "O'Reilly", 'date': datetime.date(2005, 11, 18)})
    

    3)sql注入

    SQL = "INSERT INTO authors (name) VALUES ('%s');" # NEVER DO THIS
    data = ("O'Reilly", )
    cur.execute(SQL % data) # 错误使用方法
    
    SQL = "INSERT INTO authors (name) VALUES (%s);" # Note: no quotes
    data = ("O'Reilly", )
    cur.execute(SQL, data) # 正确使用方法,使用两个参数,可以避免sql注入
    

    3.python数据类型适应psycopg数据类型

  • 相关阅读:
    格式化日期为yyyy-MM-dd
    JavaScript 原型
    SSD 车辆检测 实现
    Unity模拟自动驾驶方向盘角度预测
    交通标识牌识别
    cifar-10 No such file or directory: '/home/ /.keras/datasets/cifar-10-batches-py/data_batch_1'
    Keras 使用多层感知器 预测泰坦尼克 乘客 生还概率
    else
    Keras源码下载记录
    import cv2 失败 ImportError:DLL load fail:找不到指定模块
  • 原文地址:https://www.cnblogs.com/shijingjing07/p/7840499.html
Copyright © 2011-2022 走看看