需要Python编程技巧

时间:2016-07-13 21:58:54

标签: python mysql class optimization connection

我从最近几周开始学习python。为了更好的学习,我决定开展一些项目。所以这里是我的Class for MySQL连接和演示示例。你能告诉我吗?以下代码可以提供哪些其他改进?

  • 结构?
  • 我还可以做些什么来优化代码?

请原谅。如果我在代码中犯了一些愚蠢的错误。 (我正在学习)

#!/usr/bin/python
import pymysql

# select (table, parameter)
# insert (table, data)
# update (table, id, data)
# delete (table, id)

class MySQL:
    def __init__(self):
        self.sort_by = ""
        self.order = ""
        # initiate database connection.
        self.connection = pymysql.connect(host='localhost',
                             user='root',
                             password='',
                             db='sherlock',
                             charset='utf8mb4')

        self.cursor = self.connection.cursor(pymysql.cursors.DictCursor)
    # this function is for selecting any feild on any table.(feilds veriable is optinal)     
    def select(self, table, *feilds):
        flds = "" #differnt name for feilds veriable.
        if not feilds:
            flds = '*'
        else:
            for f in feilds:
                if not flds:
                    flds = f
                else:
                    flds += ",`%s`" % f
        sql = "SELECT %s FROM `%s` " % (flds, table)
        if self.sort_by:
            sql = sql +"order by "+ str(self.sort_by) +" "+ str(self.order)
        print sql
        self.cursor.execute(sql)
        result = self.cursor.fetchall()
        return result    

    # This function is for data sorting for Mysql; but optinal.
    # example : SELECT * FROM `users`  order by id asc
    def order_by(self, sort_by="", order="", *args, **kwargs):
        self.sort_by = sort_by
        self.order = order

    # this function is for closing Mysql connection
    def close(self):
        self.connection.close()

########### END OF MySQL CLASS #############


sql = MySQL()

# sql.order_by function should be called before the sql.select() function.
sql.order_by("email")

# this will select all the feilds from `users` table.
# you can specify whichever feilds you want to return. like : sql.select("users", "id, email")
result = sql.select("users", "password")

for email in result:
    print email["password"]
sql.close()

0 个答案:

没有答案