Title: Examples and practical guide for using Python to write stored procedures in MySQL
Using stored procedures in MySQL can effectively encapsulate complex database operations and improve Database execution efficiency and security. This article will introduce how to use Python to write MySQL stored procedures and provide specific code examples for reference.
DELIMITER // CREATE PROCEDURE insert_user(IN username VARCHAR(20), IN age INT) BEGIN INSERT INTO users (username, age) VALUES (username, age); END // DELIMITER ;
In the above code, we first use the DELIMITER keyword to separate the command delimiter Change to // because multiple SQL statements contained in the stored procedure must end with a semicolon (;). Then, use the CREATE PROCEDURE keyword to define a stored procedure named insert_user, which accepts two parameters: username and age. A specific SQL statement is written between the BEGIN and END keywords to insert a new record into the users table.
import MySQLdb def call_insert_user(username, age): db = MySQLdb.connect(host="localhost", user="root", passwd="password", db="testdb") cursor = db.cursor() try: cursor.callproc('insert_user', (username, age)) db.commit() print("存储过程成功执行") except Exception as e: db.rollback() print("存储过程执行失败:" + str(e)) db.close() # 调用存储过程 call_insert_user("John", 25)
In the above code, we first connect to the MySQL database using the MySQLdb module. Then, use the cursor.callproc function to call the stored procedure. The function accepts two parameters: the name of the stored procedure and a tuple of parameters. Finally, use db.commit() to commit the transaction and close the database connection.
Summary:
This article introduces how to use Python to write stored procedures in MySQL and provides an example of inserting records. By encapsulating complex database operations, using stored procedures can improve the execution efficiency and security of the database. I hope this article will be helpful to everyone when writing stored procedures using MySQL and Python.
The above is the detailed content of How to write stored procedures in MySQL using Python. For more information, please follow other related articles on the PHP Chinese website!