Gabriel Ferrante
Gabriel Ferrante

Reputation: 73

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. The error:

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

My python code below. I have using psycopg2 and python 3.7, in windows computer. 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)

Upvotes: 0

Views: 231

Answers (1)

Mike Organek
Mike Organek

Reputation: 12484

Short answer is to enclose the result of strptime() in single quotes:

        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.

Upvotes: 1

Related Questions