如何使用python faker填充数据库

时间:2015-05-20 09:10:44

标签: python psycopg2 psql

我正在尝试使用python faker填充表格,我收到此错误。这是我的代码

import psycopg2
from faker import Faker
fake = Faker()

conn = psycopg2.connect(database="testdb", user="****", password="****", host="127.0.0.1", port="5432")
print "Opened database successfully"
cur = conn.cursor()

for i in range (10):
    Id =fake.random_digit_not_null()
    name = fake.name()
    age=fake.random_number(digits=None) 
    adress =fake.address()
    salary = fake.random_int(min=0, max=9999)
    cur.execute("INSERT INTO COMPANY (ID,NAME,AGE,ADDRESS,SALARY) \
      VALUES (Id,name,age,adress,salary)");

conn.commit()
print "Records created successfully";
conn.close()

这是错误

Traceback (most recent call last):
  File "fakegenerator.py", line 16, in <module>
    VALUES (Id,name,age,adress,salary)");
psycopg2.ProgrammingError: column "id" does not exist
LINE 1: ...OMPANY (ID,NAME,AGE,ADDRESS,SALARY)       VALUES (Id,name,ag...
                                                             ^
HINT:  There is a column named "id" in table "company", but it cannot be referenced from this part of the query.

2 个答案:

答案 0 :(得分:3)

您没有在查询中填写值,而是按原样将字符串发送到数据库。这实际上会用值填充查询:

cur.execute("INSERT INTO COMPANY (ID,NAME,AGE,ADDRESS,SALARY) VALUES (%s, %s, %s, %s, %s)", (Id, name, age, adress, salary));

这会将填充了您要插入的值的变量包装到元组中,并让psycopg2处理正确引用您的字符串,这对您来说不那么有用,并且如果您使用代码,则可以保护您免受SQL注入的影响生产代码的基础。这在the module's documentation中有记录。

答案 1 :(得分:-1)

cur.execute中的sql请求似乎是个问题,试试这个

UPDATE attempts SET MAX_ATTEMPTS++ WHERE IP = ?