Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
386 views
in Technique[技术] by (71.8m points)

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)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...