[英]Psycopg2 can not create table
From Jupiter notebook, I was able to create Database with Psycopg2.从 Jupiter notebook 中,我能够使用 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).使用上面的代码,我可以从 psql(windows 命令提示符)看到名为“socialmedia”的数据库。
But with the below code, I can not see table named "test_table" from psql.但是使用下面的代码,我看不到 psql 中名为“test_table”的表。
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.我只能从 Jupyter notebook 获取元素,而不能从 psql 获取元素。 And it seems elements are stored temporarily.
似乎元素是临时存储的。
How can I see table and elements from psql and keep the element permanently?如何从 psql 中查看表和元素并永久保留元素?
I don't see any dbCursor.execute('commit')
in the second part of your question?我在问题的第二部分没有看到任何
dbCursor.execute('commit')
?
You have provided an example with AUTOCOMMIT which works, and you are asking why results are stored temporarly
when you are not using AUTOCOMMIT?您提供了一个 AUTOCOMMIT 的示例,该示例有效,并且您在问为什么在不使用 AUTOCOMMIT 时
results are stored temporarly
? Well, they are not commited!好吧,他们没有承诺!
They are stored only for the current session, that's why you can get it from your Jupyter session它们仅针对当前会话存储,这就是您可以从 Jupyter 会话中获取它的原因
Also:还:
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.