如何在MySQL中使用Python編寫自訂預存程序和函數
MySQL是一種常用的關係型資料庫管理系統,而Python是一種強大的程式設計語言.結合兩者可以實現更靈活和高效的資料庫操作。 MySQL中的預存程序和函數可以幫助我們封裝常用的操作邏輯,減少重複程式碼的編寫。本文將介紹如何使用Python編寫自訂預存程序和函數,並附上具體的程式碼範例。
CREATE DATABASE testdb; USE testdb; CREATE TABLE users ( id INT PRIMARY KEY AUTO_INCREMENT, name VARCHAR(255), age INT, email VARCHAR(255) );
import mysql.connector mydb = mysql.connector.connect( host="localhost", user="yourusername", password="yourpassword", database="testdb" ) mycursor = mydb.cursor()
def create_procedure(): sql = """ CREATE PROCEDURE get_users_by_age( IN min_age INT, IN max_age INT ) BEGIN SELECT * FROM users WHERE age >= min_age AND age <= max_age; END """ mycursor.execute(sql) mydb.commit()
def call_procedure(): mycursor.callproc("get_users_by_age", (18, 30)) for result in mycursor.stored_results(): for row in result.fetchall(): print(row)
def create_function(): sql = """ CREATE FUNCTION count_users_by_age( min_age INT, max_age INT ) RETURNS INT BEGIN DECLARE user_count INT; SELECT COUNT(*) INTO user_count FROM users WHERE age >= min_age AND age <= max_age; RETURN user_count; END """ mycursor.execute(sql) mydb.commit()
def call_function(): mycursor.callfunc("count_users_by_age", int, (18, 30))
import mysql.connector mydb = mysql.connector.connect( host="localhost", user="yourusername", password="yourpassword", database="testdb" ) mycursor = mydb.cursor() def create_procedure(): sql = """ CREATE PROCEDURE get_users_by_age( IN min_age INT, IN max_age INT ) BEGIN SELECT * FROM users WHERE age >= min_age AND age <= max_age; END """ mycursor.execute(sql) mydb.commit() def call_procedure(): mycursor.callproc("get_users_by_age", (18, 30)) for result in mycursor.stored_results(): for row in result.fetchall(): print(row) def create_function(): sql = """ CREATE FUNCTION count_users_by_age( min_age INT, max_age INT ) RETURNS INT BEGIN DECLARE user_count INT; SELECT COUNT(*) INTO user_count FROM users WHERE age >= min_age AND age <= max_age; RETURN user_count; END """ mycursor.execute(sql) mydb.commit() def call_function(): mycursor.callfunc("count_users_by_age", int, (18, 30)) create_procedure() call_procedure() create_function() call_function()以上就是使用Python在MySQL中編寫自訂預存程序和函數的方法,希望對你有幫助。透過合理地利用預存程序和函數,我們可以提高資料庫操作的效率和靈活性,並實現更強大的功能。
以上是如何在MySQL中使用Python編寫自訂預存程序和函數的詳細內容。更多資訊請關注PHP中文網其他相關文章!