首页 > 解决方案 > 如何共享函数内部的mysql连接?

问题描述

我是python和mysql的初学者。我有一个用 Python 编写的小应用程序,它连接到远程 mysql 服务器。连接和获取数据没有问题。它工作正常,然后代码在函数之外。由于我想关闭和打开连接,从我的应用程序中的几个函数执行不同的查询,我希望能够调用一个函数来建立连接或根据需要运行查询。似乎当我创建一个连接时,该连接不能在函数之外使用。我想实现这样的事情:

mydbConnection(): ....

我的数据库查询(): ....

已连接 = mydbConnection()

myslq = '选择 *.......'

结果 = mydbQuery(mysql)

等等...

感谢您对此的任何指导。

标签: pythonmysqldatabasefunctionconnection

解决方案


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)

推荐阅读