Menu

consecutive statements in for loop

Help
2009-05-21
2012-09-19
  • Clinton Miskell

    Clinton Miskell - 2009-05-21

    Hey guys, wondering if anyone has a better way to do this. Seems to work well, but it seems like it could be easier (no list hopefully). I have a bunch of huge queries that I keep in an external module. I assign each statement to a variable, then add the variable to a list:

    statements.py
    var1="""some insert statement"""
    var2="""some insert statement"""
    var3="""call some proceedure""" and so-on.

    list = [var1, var2, var3]


    execute.py:

    import MySQLdb, settings, mailer, statements

    def sql(statement):
    try:
    con = MySQLdb.connect (host=settings.server,user=settings.user,passwd=settings.password,db=settings.database)
    cursor = con.cursor()
    cursor.execute(statement)
    cursor.close()
    con.close

    except MySQLdb.Error, e:
        error = "Warehouse Error %d: %s" % (e.args[0], e.args[1])
        mailer.sendMail(settings.emailAddress, error, statement)
        sys.exit(1)
    

    for item in statements.list:
    sql(item)

    If anyone knows if im doing something silly here please let me know! Thanks!

     
    • Kyle VanderBeek

      Kyle VanderBeek - 2009-05-27

      That's a pretty common idiom, so I wouldn't call it silly. Mind using "list" as a variable name, though; it's not a reserved word in Python, but it is a built-in type and you could end up getting confusing results later.

      Additionally I will pimp my recent blog entry about using decorators for such standard idioms:
      http://www.kylev.com/2009/05/22/python-decorators-and-database-idioms/

       

Log in to post a comment.

Want the latest updates on software, tech news, and AI?
Get latest updates about software, tech news, and AI from SourceForge directly in your inbox once a month.