Psycopg2 can not create table

北战南征 提交于 2021-01-29 19:36:49

问题


From Jupiter notebook, I was able to create Database with Psycopg2. But somehow I was not able to create Table and store element in it.

import psycopg2
from psycopg2.extensions import ISOLATION_LEVEL_AUTOCOMMIT

con = psycopg2.connect("user=postgres password='abc'");
con.set_isolation_level(ISOLATION_LEVEL_AUTOCOMMIT);

cursor          = con.cursor();
name_Database   = "socialmedia";

sqlCreateDatabase = "create database "+name_Database+";"

cursor.execute(sqlCreateDatabase);

With the above code, I can see database named "socialmedia" from psql (windows command prompt).

But with the below code, I can not see table named "test_table" from psql.

import psycopg2

# Open a DB session
dbSession = psycopg2.connect("dbname='socialmedia' user='postgres' password='abc'");
# Open a database cursor
dbCursor = dbSession.cursor();
# SQL statement to create a table
sqlCreateTable  = "CREATE TABLE test_table(id bigint, cityname varchar(128), latitude numeric, longitude numeric);";
# Execute CREATE TABLE command
dbCursor.execute(sqlCreateTable);
# Insert statements
sqlInsertRow1  = "INSERT INTO test_table values(1, 'New York City', 40.73, -73.93)";
sqlInsertRow2  = "INSERT INTO test_table values(2, 'San Francisco', 37.733, -122.446)";


# Insert statement
dbCursor.execute(sqlInsertRow1);
dbCursor.execute(sqlInsertRow2);

# Select statement
sqlSelect = "select * from test_table";
dbCursor.execute(sqlSelect);
rows = dbCursor.fetchall();

# Print rows
for row in rows:
    print(row);

I can get elements only from Jupyter notebook, but not from psql. And it seems elements are stored temporarily.

How can I see table and elements from psql and keep the element permanently?


回答1:


I don't see any dbCursor.execute('commit') in the second part of your question?

You have provided an example with AUTOCOMMIT which works, and you are asking why results are stored temporarly when you are not using AUTOCOMMIT? Well, they are not commited!

They are stored only for the current session, that's why you can get it from your Jupyter session

Also:

  • you don't need to put semicolons in your python code
  • you don't need to put semicolons in your SQL code (except when you execute multiple statements, which is not the case here)


来源:https://stackoverflow.com/questions/60846961/psycopg2-can-not-create-table

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!