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

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

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

  1. import pandas as pd
  2. import psycopg2
  3. test=pd.DataFrame({'A':[1,1],'B':[2,2]})
  4. #connect is a function to connect to the RDS instance
  5. connection= connect()
  6. cursor=connection.cursor()
  7. query='CREATE TABLE test (A varchar NOT NULL,B varchar NOT NULL);'
  8. cursor.execute(query)
  9. connection.commit()
  10. cursor.close()
  11. connection.close()

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

  1. connection=connect()
  2. # check if file already exists in SQL
  3. sql = """
  4. SELECT "table_name","column_name", "data_type", "table_schema"
  5. FROM INFORMATION_SCHEMA.COLUMNS
  6. WHERE "table_schema" = 'public'
  7. ORDER BY table_name
  8. """
  9. file_check=pd.read_sql(sql, con=connection)
  10. connection.close()

我得到:

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

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

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

退货:

  1. Empty DataFrame
  2. Columns: [a, b]
  3. Index: []

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

aurhwmvo

aurhwmvo1#

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

  1. test_tbl.to_sql("test", connection)

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

  1. $ createdb so63284022
  2. $ python
  3. >>> import sqlalchemy as sa
  4. >>> import pandas as pd
  5. >>> test = pd.DataFrame({'A':[1,1],'B':[2,2], 'C': ['yes', 'hello']})
  6. >>> engine = sa.create_engine("postgres://localhost/so63284022")
  7. >>> with engine.connect() as connection:
  8. ... test.to_sql("test", connection)
  9. ...
  10. >>>
  11. $ psql so63284022
  12. so63284022=# select * from test;
  13. index | A | B | C
  14. -------+---+---+-------
  15. 0 | 1 | 2 | yes
  16. 1 | 1 | 2 | hello
  17. (2 rows)
  18. so63284022=# \d+ test
  19. Table "public.test"
  20. Column | Type | Collation | Nullable | Default | Storage | Stats target | Description
  21. --------+--------+-----------+----------+---------+----------+--------------+-------------
  22. index | bigint | | | | plain | |
  23. A | bigint | | | | plain | |
  24. B | bigint | | | | plain | |
  25. C | text | | | | extended | |
  26. Indexes:
  27. "ix_test_index" btree (index)
  28. Access method: heap
  29. so63284022=#
展开查看全部
qcuzuvrc

qcuzuvrc2#

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

  1. query='CREATE TABLE test (A varchar NOT NULL,B varchar NOT NULL);'
  2. cursor.execute(query)

我加上如下内容:

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

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

相关问题