简体   繁体   English

使用python将pandas数据帧插入到actian PSQL数据库表中

[英]Insert pandas dataframe into actian PSQL database table using python

I want to import data of file "save.csv" into my actian PSQL database table "new_table" but i got error我想将文件“save.csv”的数据导入到我的 actian PSQL 数据库表“new_table”中,但出现错误

ProgrammingError: ('42000', "[42000] [PSQL][ODBC Client Interface][LNA][PSQL][SQL Engine]Syntax Error: INSERT INTO 'new_table'<< ??? >> ('name','address','city') VALUES (%s,%s,%s) (0) (SQLPrepare)")

Below is my code:下面是我的代码:

   connection = 'Driver={Pervasive ODBC Interface};server=localhost;DBQ=DEMODATA'
   db = pyodbc.connect(connection)
   c=db.cursor()
    #create table i.e new_table

    csv = pd.read_csv(r"C:\Users\user\Desktop\save.csv")
    for row in csv.iterrows():
        insert_command = """INSERT INTO new_table(name,address,city) VALUES (row['name'],row['address'],row['city'])"""
        c.execute(insert_command)
        c.commit()




Pandas have a built-in function that empty a pandas-dataframe into a sql-database called pd.to_sql() . Pandas 有一个内置函数,可以将 pandas- dataframe清空到名为pd.to_sql()的 sql-database 中。 This might be what you are looking for.这可能就是您要寻找的。 Using this you dont have to manually insert one row at a time but you can insert the entire dataframe at once.使用它您不必一次手动插入一行,但您可以一次插入整个数据框。

If you want to keep using your method, the issue might be that the table "new_table" hasn't been created yet in the database.如果您想继续使用您的方法,问题可能在于数据库中尚未创建表“new_table”。 And thus you first need something like this:因此你首先需要这样的东西:

CREATE TABLE new_table 
( 
Name [nvarchar](100) NULL, 
Address [nvarchar](100) NULL, 
City [nvarchar](100) NULL
)

EDIT: You can use to_sql() like this on tables that already exist in the database:编辑:您可以像这样在数据库中已经存在的表上使用 to_sql() :

df.to_sql(
        "new_table",
        schema="name_of_the_schema",
        con=c.session.connection(),
        if_exists="append", # <--- This will append an already existing table
        chunksize=10000,
        index=False,
    )

我已经尝试过相同的方法,在我的情况下创建了表,我只想使用 Actian PSQL 将 Pandas 数据帧中的每一行插入到数据库中

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM