如何共享函数内部的 mysql 连接?
How to share a mysql connection that is inside a function?
我是 python 和 mysql 的初学者。我有一个用 Python 编写的小应用程序连接到远程 mysql 服务器。连接和获取数据没有问题。它工作正常然后代码在函数之外。由于我想关闭和打开连接,从我的应用程序中的多个函数执行不同的查询,我希望能够调用一个函数来建立连接或 运行 根据需要进行查询。似乎当我创建连接时,该连接不能在函数外使用。我想实现这样的东西:
mydbConnection():
....
mydbQuery():
....
已连接 = mydbConnection()
myslq = 'SELECT *.......'
结果 = mydbQuery(mysql)
等等...
感谢您对此的任何指导。
import mysql.connector
from mysql.connector import Error
def mydbConnection(host_name, user_name, user_password):
connection = None
try:
connection = mysql.connector.connect(
host=host_name,
user=user_name,
passwd=user_password
)
print("Connection to MySQL DB successful")
except Error as e:
print(f"The error '{e}' occurred")
return connection
connection = mydbConnection("localhost", "root", "")
在上面的脚本中,您定义了一个接受三个参数的函数 mydbConnection():
host_name
user_name
user_password
mysql.connector Python SQL 模块包含一个方法 .connect() ,您可以在第 7 行中使用它来连接到 MySQL 数据库服务器。建立连接后,连接对象将返回给调用函数。最后,在第 18 行中,您使用主机名、用户名和密码调用 mydbConnection()。
现在,要使用这个 connect
变量,这里有一个函数:
def mydbQuery(connection, query):
cursor = connection.cursor()
try:
cursor.execute(query)
print("Database created successfully")
except Error as e:
print(f"The error '{e}' occurred")
要执行查询,您可以使用游标对象。要执行的查询以字符串格式传递给 cursor.execute()。
在 MySQL 数据库服务器中为您的社交媒体应用程序创建一个名为 db 的数据库:
create_database_query = "CREATE DATABASE db"
mydbQuery(connection, create_database_query)
我是 python 和 mysql 的初学者。我有一个用 Python 编写的小应用程序连接到远程 mysql 服务器。连接和获取数据没有问题。它工作正常然后代码在函数之外。由于我想关闭和打开连接,从我的应用程序中的多个函数执行不同的查询,我希望能够调用一个函数来建立连接或 运行 根据需要进行查询。似乎当我创建连接时,该连接不能在函数外使用。我想实现这样的东西:
mydbConnection(): ....
mydbQuery(): ....
已连接 = mydbConnection()
myslq = 'SELECT *.......'
结果 = mydbQuery(mysql)
等等...
感谢您对此的任何指导。
import mysql.connector
from mysql.connector import Error
def mydbConnection(host_name, user_name, user_password):
connection = None
try:
connection = mysql.connector.connect(
host=host_name,
user=user_name,
passwd=user_password
)
print("Connection to MySQL DB successful")
except Error as e:
print(f"The error '{e}' occurred")
return connection
connection = mydbConnection("localhost", "root", "")
在上面的脚本中,您定义了一个接受三个参数的函数 mydbConnection():
host_name user_name user_password
mysql.connector Python SQL 模块包含一个方法 .connect() ,您可以在第 7 行中使用它来连接到 MySQL 数据库服务器。建立连接后,连接对象将返回给调用函数。最后,在第 18 行中,您使用主机名、用户名和密码调用 mydbConnection()。
现在,要使用这个 connect
变量,这里有一个函数:
def mydbQuery(connection, query):
cursor = connection.cursor()
try:
cursor.execute(query)
print("Database created successfully")
except Error as e:
print(f"The error '{e}' occurred")
要执行查询,您可以使用游标对象。要执行的查询以字符串格式传递给 cursor.execute()。
在 MySQL 数据库服务器中为您的社交媒体应用程序创建一个名为 db 的数据库:
create_database_query = "CREATE DATABASE db"
mydbQuery(connection, create_database_query)