我试图通过使用我编写的函数将pandas数据帧中的信息插入到数据库表中:
def insert(table_name="", name="", genere="", year=1, impd_rating=float(1)):
conn = psycopg2.connect("dbname='database1' user='postgres' password='postgres333' host='localhost' port=5433 ")
cur = conn.cursor()
cur.execute("INSERT INTO %s VALUES %s,%s,%s,%s" % (table_name, name, genere, year, impd_rating))
conn.commit()
conn.close()
当我试图像这样使用这个函数时:
^{pr2}$我得到以下语法错误:
SyntaxError: invalid syntax
PS D:\tito\scripts\database training> python .\postgres_script.py
Traceback (most recent call last):
File ".\postgres_script.py", line 56, in <module>insert (impd_rating=float(DF['idbm_rating'][b]),year=int(DF['year'][b]),name=str(DF['name'][b]),genere=str(DF['genere'][b]),table_name='test_movies')
File ".\postgres_script.py", line 15, in insert
cur.execute("INSERT INTO %s VALUES %s,%s,%s,%s" % (table_name ,name ,genere , year,impd_rating))
psycopg2.ProgrammingError: syntax error at or near "Avatar"
LINE 1: INSERT INTO test_movies VALUES Avatar,action,2009,7.9
我还试图将str替换方法从%s
改为{
你好,mohamed mahrous,
首先为access access PostgreSQL数据库安装psycopg2包。在
试试下面的代码
^{pr2}$
我希望我的回答有帮助。
如有任何疑问请评论。在
错误消息是显式的,此SQL命令在
Avatar
:INSERT INTO test_movies VALUES Avatar,action,2009,7.9
处出错。因为值必须用括号括起来,字符串必须用引号引起来,所以正确的SQL是:但是,通过串联参数来构建完整的SQL命令是错误的做法(*),只有表名应该直接插入到命令中,因为is不是SQL参数。正确的方法是使用参数化查询:
^{pr2}$(*)这是导致大量SQL注入缺陷的原因,因为如果其中一个参数包含一个半列(
;
),那么后面的内容可以解释为一个新命令Pandas对此有一个DataFrame方法,^{} :
希望这能让你朝着正确的方向前进。在
相关问题 更多 >
编程相关推荐