【问题标题】:how to populate database using python faker如何使用 python faker 填充数据库
【发布时间】:2015-05-20 09:10:43
【问题描述】:

我正在尝试使用 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.

【问题讨论】:

    标签: python psycopg2 psql


    【解决方案1】:

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

    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 中有记录。

    【讨论】:

      【解决方案2】:

      cur.execute中的sql请求好像有问题试试这个

      cur.execute("INSERT INTO COMPANY (ID,NAME,AGE,ADDRESS,SALARY) \
        VALUES ({},{},{},{},{})".format(Id,name,age,adress,salary));
      

      【讨论】:

      • 插入数据库时​​不应使用字符串连接。 xkcd.com/327 .. Psycopg2 状态:Warning Never, never, NEVER use Python string concatenation (+) or string parameters interpolation (%) to pass variables to a SQL query string. Not even at gunpoint.
      猜你喜欢
      • 1970-01-01
      • 2021-06-30
      • 2021-02-17
      • 2016-03-31
      • 2017-10-24
      • 2016-01-16
      • 2013-09-19
      • 2015-01-27
      • 2018-01-29
      相关资源
      最近更新 更多