The first type: splicing strings can solve the problem, but in order to avoid SQL injection, it is not recommended to write this way
Let’s take a look at the second one: use the .format() function. Many times I use this function to parameterize sql
for example:
select * from XX where id in (1,2,3)
Parameterize the value in in:
select * from XX where id in ({}).format(‘1,2,3’)
You can print it and see, it is exactly the same as your original SQL
Supplementary knowledge: python and mysql interaction/read local configuration file/interaction error report
If you want to read the local configuration file to write a mysql connection yourself, you need to pay attention to:
Write in the configuration file config.ini:
[ sql]
ip = xxx
port = xxx
table = xxx
uname = xxx
passwd = xxx
Such as: test.py file
# Import first
import pymysql
# This is to get the content of the configuration file
host = conf.get('sql','ip')
port = conf.get('sql','port')
database = conf.get('sql','table'),
user = conf.get('sql','uname')
password = conf.get('sql','passwd')
# Establish mysql database connection
conn = pymysql.connect(host=host, port=port, db=database, user=user, password=password, charset='utf8') #Note here that there may be an error, I will say later
sql ='xxx' #sql statement
cs1 = conn.cursor() #Create execution object
count = cs1.execute(sql) #Execute the sql statement, the return value is the number of rows affected in the database, and assigned to count
conn.commit() #Submit database changes
cs1.close() #Close execution object
conn.close() #Close the database connection object
Error:
can only concatenate tuple (not “bytes”) to tuple
This is because a certain result read in the configuration file is an array, print it and you will know
But in the last python read configuration file, I tried the first one [global] to read, but there is no array form. I don’t know why this is. Welcome everyone to leave a message and communicate together.
[ Errno 11004] getaddrinfo failed and the following
**django.db.utils.OperationalError: (2003, "Can't connect to MySQL server") error when django operates mysql: **
If an error is reported when referencing the local configuration file, this error is also likely to be a problem when reading the configuration file
You can try to solve it like this:
Either you use the tools locally or try to connect with the command. If it doesn’t work, it may be a network or permission problem.
If the above is possible, write a separate python file directly, instead of reading the local file, write the information directly in the py file, the result of the operation is OK, it is the problem of reading the configuration file
Then try to read, and print the reading results, you can find the problem
The above description of in parameterization in python mysql is all the content shared by the editor. I hope to give you a reference.
Recommended Posts