如果elif else db更新脚本,更好的python3方法

时间:2018-05-10 13:35:39

标签: python python-3.x sqlalchemy

我的代码按照下面的预期运行,但我会将其用作'模板'前进,在我制作一个巨大的文件之前,我想让它更清洁'因为我认为我做错了,即使它有效。

在我的脚本顶部可以指定数据库连接,然后在下面的函数中引用它们吗?

   def db_update(x):
if x < 30:
    connection = MySQLdb.connect (host= "localhost", REDACTED)
    cursor = connection.cursor()
    sqlcommand = """REDACTED"""
    cursor.execute(sqlcommand)
    cursor.fetchone()
    connection.commit()
    cursor.close()
    connection.close()
elif x > 270 :
    connection = MySQLdb.connect (host= "localhost", REDACTED)
    cursor = connection.cursor()
    sqlcommand = """REDACTED"""
    cursor.execute(sqlcommand)
    cursor.fetchone()
    connection.commit()
    cursor.close()
    connection.close()
else:
    connection = MySQLdb.connect (host= "localhost", REDACTED)
    cursor = connection.cursor()
    sqlcommand = """REDACTED"""
    cursor.execute(sqlcommand)
    cursor.fetchone()
    connection.commit()
    cursor.close()
    connection.close()

我想知道我是否可以看起来像这样。

def db_update(x):
connection = MySQLdb.connect (host= "localhost", REDACTED)
cursor = connection.cursor()
if x < 30:
    sqlcommand = """REDACTED"""
elif x > 270 :
    sqlcommand = """REDACTED"""
else:
    sqlcommand = """REDACTED"""
cursor.execute(sqlcommand)
cursor.fetchone()
connection.commit()
cursor.close()
connection.close()

甚至更好的是从全局或导入脚本中引用它,如此

def run_sql():
    connection = MySQLdb.connect (host= "localhost", REDACTED)
    cursor = connection.cursor()
    cursor.execute(sqlcommand)
    cursor.fetchone()
    connection.commit()
    cursor.close()
    connection.close()

def db_update(run_sql, x):
    if x < 30:
        sqlcommand = """REDACTED"""
    elif x > 270 :
        sqlcommand = """REDACTED"""
    else:
        sqlcommand = """REDACTED"""
    runsql()

非常这是新的,所以请保持温和,如果有良好的学习链接,请随时分享

0 个答案:

没有答案