【问题标题】:Python & PostgreSql: Insert Value Into Column In TablePython 和 PostgreSql:将值插入表中的列
【发布时间】:2019-09-27 14:40:43
【问题描述】:

我有以下 PostgreSql 表:

我想在诊断列下的第一行插入一个字符串值 3。我正在尝试遵循 postgresql 文档中的一些通用 INSERT 代码。以下是我工作的试用代码。

diagnosis = 3; 

pip install config

# insert 

import psycopg2
from config import config


def insert_diagnosis(diagnosis):
    """ insert a new diagnosis prediction into the eyeballtables table """
    sql = """INSERT INTO eyeballtables(diagnosis)
             VALUES(%s) RETURNING vendor_id;"""
    conn = None
    vendor_id = None
    try:
        # read database configuration
        params = config()
        # connect to the PostgreSQL database
        conn = psycopg2.connect(**params)
        # create a new cursor
        cur = conn.cursor()
        # execute the INSERT statement
        cur.execute(sql, (diagnosis,))
        # get the generated id back
        vendor_id = cur.fetchone()[0]
        # commit the changes to the database
        conn.commit()
        # close communication with the database
        cur.close()
    except (Exception, psycopg2.DatabaseError) as error:
        print(error)
    finally:
        if conn is not None:
            conn.close()

    return vendor_id

上面的代码并不完全正确,因为它没有将插入隔离到表中的“诊断”字段。但除此之外,即使我成功 pip 安装了配置,我也会收到以下错误:

ImportError: cannot import name 'config' from 'config' (/home/pinzhi/anaconda3/lib/python3.7/site-packages/config.py)

想想我做错了什么,或者是否有更直接的方法可以将数据点插入到我拥有的 PostgreSql 表中?

编辑 ---------------------------------- ---------------------- 在我遵循提供的答案后,不再弹出配置错误。但是我上面的代码无法将诊断值 3 插入表中。

我做错了什么?

【问题讨论】:

  • 你为什么要运行pip install inside你的脚本?
  • 什么是config 模块?
  • 你为什么要pip install呢? config 大概是本地文件吧?
  • @roganjosh:我应该在哪里运行它?
  • 您插入行,而不是字符串。如果要将字符串添加到现有行,则需要 UPDATE。

标签: python database postgresql function insert


【解决方案1】:

这是配置而不是配置

from config import Config
params = Config()

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-01-09
    • 2020-02-20
    相关资源
    最近更新 更多