当涉及到需要访问数据库的函数时,我正在尝试弄清楚如何配置多个MySQL数据库之间的连接;一个存在于 import { browser } from '$app/env';
// browser is true or false depending on whether the app is running in the browser or on the server
中,另一个存在于 main.py
。这样当我将函数从 main.py 导入到 test.py 时,函数会针对测试数据库执行。
这是我第一次使用 MySQL/Python 连接器,所以我不确定如何实现这一点。
main.py
test.py
答案 0 :(得分:0)
它实际上比你想象的要简单,你必须像这样创建一个全局的 mysql 连接器变量,
mydb = mysql.connector.connect(
host="localhost",
user="yourusername",
password="yourpassword"
database = "databasename"
)
此时您可以将其用作函数的参数,
#main.py
def exampleFunc(mydb):
mycursor = mydb.cursor()
mycursor.execute("SELECT * FROM example")
return mycursor.fetchall()
#test.py
mydb = mysql.connector.connect(
host="localhost",
user="yourusername",
password="yourpassword"
database = "test_database"
)
val = exampleFunction(mydb)