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

posted on 2017-11-15 19:09  迪米特  阅读(485)  评论(0编辑  收藏  举报

导航