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数据类型

  • 相关阅读:
    python函数
    python文件IO操作
    LAMP项目上线
    linux下的小工具
    linux下自有服务
    Lesson_Swift2
    枚举
    使用文件流下载附件
    Global中的Timer计时器
    IE11下的NPOI导出提示__doPostBack未定义解决方案
  • 原文地址:https://www.cnblogs.com/shijingjing07/p/7840499.html
Copyright © 2011-2022 走看看