psycopg2 postgres数据库在valu附近出现语法错误

2024-09-28 19:25:12 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图通过使用我编写的函数将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改为{} 但我也犯了同样的错误。在


Tags: namedftablescriptpostgresconnyearinsert
3条回答

你好,mohamed mahrous,

首先为access access PostgreSQL数据库安装psycopg2包。在

试试下面的代码

import psycopg2
conn=psycopg2.connect("dbname='database1' user='postgres' password='postgres333' host='localhost' port=5433 ")
cur=conn.cursor()

def insert(table_name,name,genere,year,impd_rating): 
    query = "INSERT INTO "+table_name+"(name,genere,year,impd_rating) VALUES(%s,%s,%s,%s)"
    try:
        print query
        cur.execute(query,(name,genere,year,impd_rating))
    except Exception, e:
        print "Not execute..."
    conn.commit()

b=0
for row in DF['id']:
    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')
    b= b+1

conn.close()

^{pr2}$

我希望我的回答有帮助。
如有任何疑问请评论。在

错误消息是显式的,此SQL命令在Avatar:INSERT INTO test_movies VALUES Avatar,action,2009,7.9处出错。因为值必须用括号括起来,字符串必须用引号引起来,所以正确的SQL是:

INSERT INTO test_movies VALUES ('Avatar','action',2009,7.9)

但是,通过串联参数来构建完整的SQL命令是错误的做法(*),只有表名应该直接插入到命令中,因为is不是SQL参数。正确的方法是使用参数化查询:

^{pr2}$

(*)这是导致大量SQL注入缺陷的原因,因为如果其中一个参数包含一个半列(;),那么后面的内容可以解释为一个新命令

Pandas对此有一个DataFrame方法,^{}

# Only needs to be executed once.
conn=psycopg2.connect("dbname='database1' user='postgres' password='postgres333' host='localhost' port=5433 ")


df.to_sql('test_movies', con=conn, if_exists='append', index=False)

希望这能让你朝着正确的方向前进。在

相关问题 更多 >