zoukankan      html  css  js  c++  java
  • python连接PostgreSQL

    1. 常用模块

    # 连接数据库

    connect()函数创建一个新的数据库连接对话并返回一个新的连接实例对象

    PG_CONF_123 = {
        'user':'emma',
        'port':123,
        'host':'192.168.1.123',
        'password':'emma',
        'database':'dbname'}
    conn = psycopg2.connect(**PG_CONF_123)
    

    # 打开一个操作整个数据库的光标

    连接对象可以创建光标用来执行SQL语句

    cur = conn.cursor()
    

    # 执行一个创建表的SQL语句

    光标可以使用execute()和executemany()函数

    cur.execute("CREATE TABLE test (id serial PRIMARY KEY, num integer, data varchar);")
    

    # 传递参数给插入语句

    cur.execute("INSERT INTO test (num, data) VALUES (%s, %s)",(100, "abc'def"))
    

    # 执行查询语句并将获取到的数据作为python对象

    cur.execute("SELECT * FROM test;")
    cur.fetchone()
    (1, 100, "abc'def")
    

     

    提交修改

    如果只使用查询语句不用commit方法,insert/update/delete等操作需要调用commit()。rollback()函数用于会滚到上次调用commit()方法之后。

    conn.commit()
    

    # 关闭数据库连接

    cur.close()
    conn.close()
    

    2. 防范SQL注入漏洞

    典型的SQL注入漏洞形式:

    SQL = "select * from userinfo where id = '%s'" % (id)

    SQL = "select * from userinfo where id = '{}'".format(id)

    如果有人恶意攻击,在传入参数的代码中加入恶意代码,如:

    request.id = '123; drop tabel userid;'

    会造成严重风险,为防止此问题,应该通过第二位变量传入参数的方法:%s(无论变量是什么数据类型,都使用%s)

    SQL = "INSERT INTO authors (name) VALUES (%s);" # Note: no quotes
    data = ("O'Reilly", )
    cur.execute(SQL, data) # Note: no % operator
    
  • 相关阅读:
    StrutsTestCase 试用手记
    java版的SHA1
    看看junit在一个具体的项目中
    store/index.js中引入并注册modules目录中的js文件:require.context
    vue项目报错:$ is not defined
    状态合并:replaceState
    路由导航守卫中document.title = to.meta.title的作用
    vue路由中meta的作用
    BCryptPasswordEncoder加密与MD5加密
    滑块验证机制
  • 原文地址:https://www.cnblogs.com/guoxueyuan/p/7772435.html
Copyright © 2011-2022 走看看