python 操作postgres

python 操作postgres

问题描述

psycopg2.ProgrammingError: no results to fetch
在这里插入图片描述

import psycopg2


def exe_data(name, age):
    sql = cur.execute('INSERT INTO sample_table VALUES(%s, %s)', (name, age))
    # 执行sql
    cursor.execute(sql)
    data = cursor.fetchall() 
    
# 连接数据库
conn = psycopg2.connect(database = 'map-dev', user = 'postgres', password = '123456', host = '192.168.1.12', port = '5432')
cursor=conn.cursor()
exe_data("name","wm")
# 关闭指针,数据库
cursor.close()
conn.close()

实践中发现:cursor.fetchall() 修改成cursor.fetchone() 依旧会报错
正确的解决方法:cursor.fetchall()注释调,新增conn.commit()

import psycopg2


def exe_data(name, age):
    sql = cur.execute('INSERT INTO sample_table VALUES(%s, %s)', (name, age))
    # 执行sql
    cursor.execute(sql)
    # data = cursor.fetchall() 
    
# 连接数据库
conn = psycopg2.connect(database = 'map-dev', user = 'postgres', password = '123456', host = '192.168.1.12', port = '5432')
cursor=conn.cursor()
exe_data("name","wm")
# (新增)提交
conn.commit()
# 关闭指针,数据库
cursor.close()
conn.close()

数据库刷新可获取最新的插入内容

psycopg2的bug

声明

1)本文来源项目实践,已经过测试,文章存在任何问题或疑问,请留言,感谢您的阅读!
2)原创不易,转载请标注来源,感谢!
3)made in wmgis

你可能感兴趣的:(python,DataBase,python,1024程序员节)