【问题标题】:Not able to insert data into postgresql table via python script无法通过 python 脚本将数据插入到 postgresql 表中
【发布时间】:2021-06-12 03:16:29
【问题描述】:

我想将数据插入 Postgresql 数据库表并使用 python 命令行界面返回该行的 id。

代码通过 cmd 运行: python final1.py -c configuration.yml -a 'ABC'

我正在尝试从 YAML 文件加载配置。 -a 就像一个标志,表示需要在表中插入数据('ABC')

我的 file1.py python 代码:

# Import our libraries
import os
import sys
import argparse
import yaml

def add_file(configuration, studName):
    studName=str(studName)

    sql = '''INSERT INTO study(studName) VALUES(%s) RETURNING id);'''
 
    return select(configuration["connection_string"], sql, {'name':studName})

def load_configuration(configuration):
    try:
        with open(configuration, "r") as yamlfile:
            cfg = yaml.load(yamlfile)
            return cfg
    except Exception:
        print("Configuration file not found")
        exit(1)

def select(connectionString,sql,parameters):
    # Open the connection
    connection = psycopg2.connect(connectionString)
    
    cursor = connection.cursor()
    cursor.execute(sql, (parameters,))
    
    study_id=cursor.fetchone()[0]
    
    connection.commit()
    
    cursor.close()
    
    return study_id


if __name__ == "__main__":
    # Check the command line   

    # Parse the parameters
    parser = argparse.ArgumentParser()
    parser.add_argument('-a', action='store', dest='studyname')
    
    parser.add_argument('-c', action='store', dest='conf_file')
    args = parser.parse_args()
    #configuration=args.conf_file
    studies=0

    # Run the main function
    cfg = load_configuration(args.conf_file)
    studies = add_file(cfg, args.studyname)
    print(studies)
    #configuration = str(sys.argv[1:])
    #print(configuration)

我的配置文件包含连接字符串:

connection_string:"host=localhost dbname=postgres user=postgres password=pass connect_timeout=60"

我得到的错误是:

File "final1.py", line 64, in <module>
    studies = add_file(cfg, args.studyname)
  File "final1.py", line 19, in add_file
    return select(configuration["connection_string"], sql, {'name':studName})
TypeError: string indices must be integers

请帮忙

【问题讨论】:

  • 可能缺少端口?如果您删除RETURNING id,它也会插入
  • 您的 yaml 加载返回的是字符串,而不是字典。这不是你所期望的吗?顺便说一句,您的 SQL 中存在语法错误。你有一个悬空的紧括号作为倒数第二个字符。
  • 你错过了 yaml 文件中冒号后面的空格,这就是它被解析为字符串的原因

标签: python postgresql command-line-interface command-line-arguments


【解决方案1】:

正如@NobbyNobbs 正确提到的,连接字符串在冒号后没有空格。此外,正如@Tim Roberts 所指出的,我的 sql 查询有一个接近的括号,这也是错误的原因。感谢您指出错误:)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-11-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-10-31
    • 1970-01-01
    • 2014-10-24
    相关资源
    最近更新 更多