无法使用我的 python 脚本保存 PostgreSQL 中的更改
我尝试在我的 python 脚本中运行查询,在我的控制台中,我看到它们执行正常,但是当我看到我的 Postgre 数据库并且更改没有出现
_DATABASE = 'DB'
_USERNAME = 'XXXXXXX'
_PASSWORD = 'XXXXXXX'
_DB_PORT = '5432'
_HOST = '127.0.0.1'
conection_DB = None
cursor = None
try:
connection_DB = psycopg2.connect(
host=_HOST,
dbname=_DATABASE,
user=_USERNAME,
password=_PASSWORD,
port=_DB_PORT)
cursor = connection_DB.cursor()
query1 = 'UPDATE samples SET sample_code=%s, sample_type=%s WHERE sampleid=%s'
query2 = 'INSERT INTO samples(sample_code, sample_type) VALUES(%s, %s)'
query3 = 'DELETE FROM samples WHERE sample_internal_id=%s'
query4 = 'SELECT * FROM samples'
#SELECT QUERY 1
cursor.execute(query4)
for record in cursor.fetchall():
print(record)
#INSERT QUERY
values2 = ('rrr-rrr', 'SampleType1')
cursor.execute(query2, values2)
#UPDATE QUERY
values1 = ('jjj-jjj', 'SampleTyp2', 5)
cursor.execute(query1, values1)
#SELECT QUERY 2
cursor.execute(query4)
for record in cursor.fetchall():
print(record)
except Exception as error:
print('Error in DataBase communication')
在控制台中时,我看到我的“SELECT QUERY 2”显示其他查询有效并保存在我的数据库中,但从 PgAdmin 我发现事实并非如此。
I try to run queries in my python script, and in my console, I see that they execute ok, but when I see my Postgre DataBase and the changes don't appear
_DATABASE = 'DB'
_USERNAME = 'XXXXXXX'
_PASSWORD = 'XXXXXXX'
_DB_PORT = '5432'
_HOST = '127.0.0.1'
conection_DB = None
cursor = None
try:
connection_DB = psycopg2.connect(
host=_HOST,
dbname=_DATABASE,
user=_USERNAME,
password=_PASSWORD,
port=_DB_PORT)
cursor = connection_DB.cursor()
query1 = 'UPDATE samples SET sample_code=%s, sample_type=%s WHERE sampleid=%s'
query2 = 'INSERT INTO samples(sample_code, sample_type) VALUES(%s, %s)'
query3 = 'DELETE FROM samples WHERE sample_internal_id=%s'
query4 = 'SELECT * FROM samples'
#SELECT QUERY 1
cursor.execute(query4)
for record in cursor.fetchall():
print(record)
#INSERT QUERY
values2 = ('rrr-rrr', 'SampleType1')
cursor.execute(query2, values2)
#UPDATE QUERY
values1 = ('jjj-jjj', 'SampleTyp2', 5)
cursor.execute(query1, values1)
#SELECT QUERY 2
cursor.execute(query4)
for record in cursor.fetchall():
print(record)
except Exception as error:
print('Error in DataBase communication')
In console, I see that my "SELECT QUERY 2" shows that the other queries worked and were saved in my database, but from PgAdmin I see that isn't true.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
我认为您错过了“提交”功能。因为您仅执行查询而无需将查询提交DB。
您可以在上次查询执行
引用之后添加提交:
在这里
I think you missed the "commit" function. Because you only execute the query without committing the query to the DB.
You can add the commit after the last query execute
References:
here
解决了!
使用
connection.commit()
将更改保存到数据库中。SOLVED!
use
connection.commit()
to save changes in database.