I tried to query some data from mysql database, but i couldn't fetch any data even though the data is indeed exist in the database and there is no error message whatsoever.
mysql_config={
'user' : 'root',
'password' : '*********',
'host' : '*******',
'database' : 'aa_dev',
'port' : 3306
}
sql = 'SELECT idfi, aircraft, file_location FROM flights_info WHERE idfi =%s'
val = [('PK-YSG-23001',), ('PK-YSG-23002',), ('PK-YSG-23003',), ('PK-YSG-23004',)]
mydb = mysql.connector.connect(**mysql_config)
mycursor = mydb.cursor()
mycursor.executemany(sql, val)
d = mycursor.fetchall()
mycursor.close()
print(d) #Output an empty list
Then I tried query only one data and get the result. But i still don't understand why can't i query the data in bulk?.
sql = 'SELECT idfi, aircraft, file_location FROM flights_info WHERE idfi =%s'
val = ('PK-YSG-23001',)
mydb = mysql.connector.connect(**mysql_config)
mycursor = mydb.cursor()
mycursor.execute(sql, val)
d = mycursor.fetchall()
mycursor.close()
print(d) #Output the data
What I did below is instead of using the executemany
, I modified the query to use an IN
clause. This will allow us to fetch all the desired rows in one go.
sql = 'SELECT idfi, aircraft, file_location FROM flights_info WHERE idfi IN (%s)'
placeholders = ', '.join(['%s'] * len(val))
flattened_values = [item for sublist in val for item in sublist]
mydb = mysql.connector.connect(**mysql_config)
mycursor = mydb.cursor()
mycursor.execute(sql % placeholders, flattened_values)
d = mycursor.fetchall()
mycursor.close()
print(d)