简体   繁体   English

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

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

I have a problem inserting data into PostgreSQL with Python, but showing this error for me.我在使用 Python 将数据插入 PostgreSQL 时遇到问题,但对我显示了此错误。 The error:错误:

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

My python code below.我的 python 代码如下。 I have using psycopg2 and python 3.7, in windows computer.我在 windows 计算机中使用了 psycopg2 和 python 3.7。 Thanks very much非常感谢

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)

Short answer is to enclose the result of strptime() in single quotes:简短的回答是将strptime()的结果用单引号括起来:

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

The longer answer is to rewrite your code to use parameters per the warning found here .更长的答案是根据此处找到的警告重写您的代码以使用参数。

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

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