Can';t使用python创建postgresql表

Can';t使用python创建postgresql表,python,postgresql,psycopg2,Python,Postgresql,Psycopg2,我试图用json文件创建表,其中包含从Bigquery下载的数据库中每个表的字段名和类型。SQL请求对我来说很好,但是没有根据psql命令行解释器键入创建表\d 因此,首先,我尝试了一个更简单的sql请求,它也不起作用, 代码如下: import pandas as pd import psycopg2 # information used to create a database connection sqluser = 'postgres' dbname = 'testdb' pwd =

我试图用json文件创建表,其中包含从Bigquery下载的数据库中每个表的字段名和类型。SQL请求对我来说很好,但是没有根据psql命令行解释器键入创建表\d 因此,首先,我尝试了一个更简单的sql请求,它也不起作用, 代码如下:

import pandas as pd
import psycopg2

# information used to create a database connection
sqluser = 'postgres'
dbname = 'testdb'

pwd = 'postgres'
# Connect to postgres database
con = psycopg2.connect(dbname=dbname, user=sqluser, password=pwd )
curs=con.cursor()

q="""set search_path to public,public ;
CREATE TABLE tab1(
i INTEGER
);
"""

curs.execute(q)

q = """
SELECT table_name
FROM information_schema.tables
       WHERE table_schema='public'
       AND table_type='BASE TABLE';
    """

df = pd.read_sql_query(q, con)
print(df.head())
print("End of test")
上面编写的代码显示了这个新表tab1,但实际上,在psql命令行解释器中键入\d时,这个新表并没有列出。如果我输入psql解释器:

SELECT table_name
      FROM information_schema.tables
       WHERE table_type='BASE TABLE';
它也没有被列出,似乎没有实际创建,提前感谢您的帮助

缺少一个commit()调用,该调用必须在表创建sql请求之后写入, 此代码适用于:

import pandas as pd
import psycopg2

# information used to create a database connection
sqluser = 'postgres'
dbname = 'testdb'

pwd = 'postgres'
# Connect to postgres database
con = psycopg2.connect(dbname=dbname, user=sqluser, password=pwd )
curs=con.cursor()

q="""set search_path to public,public ;
CREATE TABLE tab1(
i INTEGER
);
"""

curs.execute(q)
con.commit()
q = """
SELECT table_name
FROM information_schema.tables
       WHERE table_schema='public'
       AND table_type='BASE TABLE';
    """

df = pd.read_sql_query(q, con)
print(df.head())
print("End of test")