psycopg2:cursor.execute只存储表结构,不存储数据

dwthyt8l  于 2021-07-24  发布在  Java
关注(0)|答案(2)|浏览(407)

我正在尝试使用psycopg2将代码中创建的一些表存储在rds示例中。脚本运行正常,我可以看到表正确地存储在数据库中。但是,如果尝试检索查询,则只会看到列,而不会看到数据:

import pandas as pd
    import psycopg2 

    test=pd.DataFrame({'A':[1,1],'B':[2,2]})

    #connect is a function to connect to the RDS instance
    connection= connect() 
    cursor=connection.cursor()

    query='CREATE TABLE test (A varchar NOT NULL,B varchar NOT NULL);'

    cursor.execute(query)

    connection.commit()

    cursor.close()
    connection.close()

此脚本运行时没有问题,正在打印输出 file_check 从以下脚本:

connection=connect()
   # check if file already exists in SQL
   sql = """
    SELECT "table_name","column_name", "data_type", "table_schema"
    FROM INFORMATION_SCHEMA.COLUMNS
    WHERE "table_schema" = 'public'
    ORDER BY table_name  
    """
   file_check=pd.read_sql(sql, con=connection)

   connection.close()

我得到:

table_name column_name          data_type table_schema
0       test           a  character varying       public
1       test           b  character varying       public

看起来不错。
但是,运行以下命令:

read='select * from public.test'
   df=pd.read_sql(read,con=connection)

退货:

Empty DataFrame
Columns: [a, b]
Index: []

有人知道为什么会这样吗?我好像绕不开这个

aurhwmvo

aurhwmvo1#

呃,你的第一个剧本 test_tbl dataframe,但在定义之后从未被引用。
你需要

test_tbl.to_sql("test", connection)

或者类似于写它。
一个简单的例子:

$ createdb so63284022
$ python
>>> import sqlalchemy as sa
>>> import pandas as pd
>>> test = pd.DataFrame({'A':[1,1],'B':[2,2], 'C': ['yes', 'hello']})
>>> engine = sa.create_engine("postgres://localhost/so63284022")
>>> with engine.connect() as connection:
...     test.to_sql("test", connection)
...
>>>
$ psql so63284022
so63284022=# select * from test;
 index | A | B |   C
-------+---+---+-------
     0 | 1 | 2 | yes
     1 | 1 | 2 | hello
(2 rows)

so63284022=# \d+ test
                                   Table "public.test"
 Column |  Type  | Collation | Nullable | Default | Storage  | Stats target | Description
--------+--------+-----------+----------+---------+----------+--------------+-------------
 index  | bigint |           |          |         | plain    |              |
 A      | bigint |           |          |         | plain    |              |
 B      | bigint |           |          |         | plain    |              |
 C      | text   |           |          |         | extended |              |
Indexes:
    "ix_test_index" btree (index)
Access method: heap

so63284022=#
qcuzuvrc

qcuzuvrc2#

我能够解决这个问题:正如@akx所指出的,我只是在创建表结构,而不是填充表。
我现在导入 import psycopg2.extras 在这之后:

query='CREATE TABLE test (A varchar NOT NULL,B varchar NOT NULL);'

   cursor.execute(query)

我加上如下内容:

update_query='INSERT INTO test(A, B) VALUES(%s,%s) ON CONFLICT DO NOTHING' 
   psycopg2.extras.execute_batch(cursor, update_query, test.values)

   cursor.close()
   connection.close()

我的表在与检查后已正确填充 pd.read_sql

相关问题