Python MySQL -函数查询和主菜单内的语句(数据库连接)?



我正在一个项目中工作,从mysql数据库读取和更新数据。我需要几个函数来执行不同的操作。我在菜单中向用户显示它们。我做了一些关于如何组织代码的研究,但我仍然有一些疑问。

我明白使用上下文管理器db连接和游标是最佳实践。此外,我理解只使用一个db连接和一个游标对象是优化代码和避免服务器连接过载的最佳选择。我是正确的吗?遵循这一思路,我按照如下方式组织代码:

# Database connection base class
class Database:
# Setup connection 
def __init__(self):
# data (host, pass, port, etc)
# Start connection
def __enter__(self):
# create and return connection object
# Disconnect
def __exit__(self, exc_type, exc_value, exc_tb):
# close() connection
# Functions
def function_1(self, cursor):
cursor.execute(query1)   
def function_2(self, cursor):
cursor.execute(query2)   
def function_3(self, cursor):
cursor.execute(query3)
# Cursor base class
class Cursor:
def __enter__(self):
# create and return cursor object
def __exit__(self, exc_type, exc_value, exc_tb):
# close() cursor
# main.py
with Database() as db:
with Cursor() as cursor:
while True:
print("MAIN MENU")
option = input("1. function 1n2. function 2n3.function 3n4. Exit")

if option == '1':
db.function_1(cursor)
if option == '2':
db.function_2(cursor)
if option == '3':
db.function_3(cursor)
if option == '4':
sys.exit()

我的问题:

  1. 是否可以在with块中拥有主菜单(无限循环)?
  2. 是否可以只使用一个连接和一个游标,为几个功能?如果是,它是正确的实现像前面的代码?如果没有,我是否应该为每个函数开始一个新的连接和光标?

作为参考的帖子:正确管理数据库资源:游标和连接

https://dev.to/c_v_ya/sql-cursor-via-context-manager-2gc7

我不确定我完全理解你所遇到的问题。这个问题更多的是关于正确的/被接受的做法吗?还是你实现代码的方式有问题?

通常当我连接到SQL Server我定义它如下:

cnxn = pyodbc.connect("Driver={ODBC Driver 17 for SQL Server};"
"Server=xxx;"
"Database=xxx;"
"Trusted_connection=xx;"
"UID=xxx;"
"PWD=xxx;")
# Connect to database
cursor = cnxn.cursor()

如果我理解正确,您正试图触发基于用户输入/选择的查询。大概这些查询是有限的吧?

无论如何,回到无限循环的问题。简而言之,是的,你可以做到。但是,根据具体情况,您可能会找到另一种选择。无论哪种方式,您都可能希望根据所使用的操作系统更改实现,如以下答案:

窗口:这里Unix:

最新更新