繁体   English   中英

使用 Python 插入 PostgreSQL 错误“在“17”或附近出现语法错误”

[英]Insert in PostgreSQL with Python Error “syntax error at or near ”17“ ”

我在使用 Python 将数据插入 PostgreSQL 时遇到问题,但对我显示了此错误。 错误:

syntax error at or near "17"
LINE 30:                 2021-01-05 17:38:59)

我的 python 代码如下。 我在 windows 计算机中使用了 psycopg2 和 python 3.7。 非常感谢

try:
        dados = GetDatasClimaTempo()
        con = psycopg2.connect(host='localhost', database='banco_arduino', user='gabriel', password='password')
        cur = con.cursor()

        sql = f"""insert into estacao_app_registrometeorologico
                (temperaturaAmbiente, 
                radiacaoDifusa, 
                radiacaoGlobal,
                pressao, 
                altitudeReal, 
                indiceUltravioleta, 
                precipitacaoInstantanea, 
                precipitacaoAcumulada, 
                umidade, 
                velocidadeVento, 
                direcaoVento,
                anguloVento, 
                radiometroTermico, 
                timestamp)
                values 
                ({dados['temperatura']},
                {truncate(random.uniform(10.5, 100.5),2)},
                {truncate(random.uniform(10, 3000),2)},
                {dados['pressao']},
                {truncate(random.uniform(10.5, 100.5),2)},
                {truncate(random.uniform(1, 11),2)},
                {truncate(random.uniform(10.5, 100.5),2)},
                {truncate(random.uniform(1, 15),2)},
                {dados['umidade']},
                {dados['velocidadeVento']},
                {dados['direcaoVento']},
                {truncate(random.uniform(0, 360),2)},
                {truncate(random.uniform(10.5, 100.5),2)},
                {datetime.datetime.strptime(dados['timestamp'], '%Y-%m-%d %H:%M:%S')})"""

        
        cur.execute(sql)
        con.commit()
        cur.execute('select * from estacao_app_registrometeorologico')
        recset = cur.fetchall()
        for rec in recset:
            print (rec)
        con.close()
    except Exception as ex:
        print(ex)

简短的回答是将strptime()的结果用单引号括起来:

        sql = f"""insert into estacao_app_registrometeorologico
                 ...
               '{datetime.datetime.strptime(dados['timestamp'], '%Y-%m-%d %H:%M:%S')}')"""

更长的答案是根据此处找到的警告重写您的代码以使用参数。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM