简体   繁体   中英

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

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() . 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. 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:

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 数据帧中的每一行插入到数据库中

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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