Home >Database >Mysql Tutorial >How can I efficiently execute prepared statements with MySQL in Python?
When developing Python code, it's often necessary to interact with SQL databases using prepared statements. This allows for効率更高的执行and protection against SQL injection attacks.
In your code, you're encountering a syntax error when trying to use the "PREPARE" and "EXECUTE" statements directly. This is because Python does not have its own mechanism for prepared statements and you should use the capabilities of the MySQLdb library instead.
The corrected code should look like this:
sql = ('INSERT INTO {} (date, time, tag, power) VALUES ' '(%s, %s, %s, %s)'.format(self.db_scan_table)) for (d, t, tag, power) in <your loop>: self.cursor.execute(sql, (d, t, tag, power))
Alternatively, you can use the execute_many() method of the cursor object to insert multiple rows at once:
data = [(d, t, tag, power) for <your loop>] self.cursor.executemany(sql, data)
This will significantly improve performance, especially for large datasets.
The above is the detailed content of How can I efficiently execute prepared statements with MySQL in Python?. For more information, please follow other related articles on the PHP Chinese website!