Python and MySQL query with quotes

2024/10/11 22:21:20

With a script in Python3, after extracting some strings from a file, they should be used as data to be inserted into a MySQL database as follows:

query1 = """INSERT INTO {:s} VALUES ({:s}, {:s}, {:s}, {:s});""".format(table1,"""0""",string1,string2,string3)
cursor1.execute(query1)

Some of the strings contain different and unpleasant quotes, like:

a "'double quoted'" example string

If I define some example strings with triple quotes delimiters

string1 = """a "'double quoted'" example string"""

the above query is successful. If instead the strings are returned by a function after parsing an external file, the query generates an error:

_mysql_exceptions.ProgrammingError: (1064, 'You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near \'first string, "\'Quoted part\'" of second string, , Third string\' at line 1')

I tried also with:

query1 = """INSERT INTO {:s} VALUES ('{:s}', '{:s}', '{:s}', '{:s}');""".format(table1,"""0""",string1,string2,string3)

but the same error is generated.

Also

query1 = """INSERT INTO %s VALUES (%s, %s, %s, %s);"""
data1 = ("""table1"""","""0""",string1,string2,string3)
cursor1.execute(query1,data1)

and

query1 = """INSERT INTO %s VALUES ('%s', '%s', '%s', '%s');"""
data1 = ("""table1"""","""0""",string1,string2,string3)
cursor1.execute(query1,data1)

generate the same error.

How to fix this? Maybe, once the strings have been returned by the function, is it possible to re-define them with triple quotes?

Answer

This is how you add parameters to a statement.

sql = "INSERT INTO my_table VALUES (%s, %s, %s);"cursor.execute(sql, [string1, string2, string3])

See MySQLCursor.execute().

In this example you don't have to explicitly quote the values because you're not gluing them into your SQL. Also, this is safer, because if the string contains an end quote and them some malicious SQL, it will not be executed.

You can't add the table name as a parameter, so if that was in a variable you would have to glue that into your SQL:

sql = "INSERT INTO {} VALUES (%s, %s, %s);".format(table_name)
https://en.xdnf.cn/q/118273.html

Related Q&A

Using scipy kmeans for cluster analysis

I want to understand scipy.cluster.vq.kmeans. Having a number of points distributed in 2D space, the problem is to group them into clusters. This problem came to my attention reading this question and …

Scrapy and celery `update_state`

I have the following setup (Docker):Celery linked to Flask setup which runs the Scrapy spider Flask setup (obviously) Flask setup gets request for Scrapy -> fire up worker to do some workNow I wish …

SPIDEV on raspberry pi for TI DAC8568 not behaving as expected

I have a Texas Instruments DAC8568 in their BOOST breakout board package. The DAC8568 is an 8 channel, 16bit DAC with SPI interface. The BOOST package has headers to connect it to my raspberry pi, an…

Tensorflow: Simple Linear Regression using CSV data

I am an extreme beginner at tensorflow, and i was tasked to do a simple linear regression using my csv data which contains 2 columns, Height & State of Charge(SoC), where both values are float. In …

How to resolve positional index error in python while solving a condition in python?

I have the following data and I am trying the following code: Name Sensex_index Start_Date End_Date AAA 0.5 20/08/2016 25/09/2016 AAA 0.8 26/08/2016 …

Google Calendar API: Insert multiple events (in Python)

I am using the Google Calendar API, and have successfully managed to insert a single event into an authorized primary calendar, but I would like to hard code multiple events that, when executed, would …

Remove special characters from column headers

I have a dictionary (data_final) of dataframes (health, education, economy,...). The dataframes contain data from one xlsx file. In one of the dataframes (economy), the column names have brackets and s…

Python Flask application getting OPTIONS instead of POST

I have a python Flask listener waiting on port 8080. I expect another process to make a series of POSTs to this port.The code for listener is as follows.#!/usr/bin/env python2 from __future__ import pr…

Raspberry pi:convert fisheye image to normal image using python

I have attached the USB webcam with raspberry pi to capture image and write code to send it using mail. It captures image using fswebcam commamnd so code for capture image in python script is :subproce…

modifying python daemon script, stop does not return OK (but does kill the process)

Following on from the previous post, the script now start and stops the python script (and only that particular script) correctly but does not report the OK back to the screen...USER="root" A…