python - 如何共享函数内部的mysql连接?
问题描述
我是python和mysql的初学者。我有一个用 Python 编写的小应用程序,它连接到远程 mysql 服务器。连接和获取数据没有问题。它工作正常,然后代码在函数之外。由于我想关闭和打开连接,从我的应用程序中的几个函数执行不同的查询,我希望能够调用一个函数来建立连接或根据需要运行查询。似乎当我创建一个连接时,该连接不能在函数之外使用。我想实现这样的事情:
mydbConnection(): ....
我的数据库查询(): ....
已连接 = mydbConnection()
myslq = '选择 *.......'
结果 = 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():
主机名用户名用户密码
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)
推荐阅读
- image - 如何将 p5.js 画布保存为非常大的 PNG?
- scala - 多种类型时的Scala差异
- ios - 设置 firebase_messaging 后在 Iphone 上安装卡住
- javascript - 如何在没有 jquery 的情况下隐藏 Internet Explorer 中的元素?
- cgal - CAD中的几何内核
- javascript - D3(v5) 可折叠树与搜索
- azure-logic-apps - Azure 逻辑应用:For Each 循环中的 HTTP POST 显示未经授权的错误
- python - python scipy stats cdf beta-pert 计算返回 nan
- date - Flatline:如何计算两个日期之间的天数
- postgresql - Objection.js 渴望多对多关系问题