Python类数据库构造函数

时间:2017-07-04 03:46:46

标签: python sql-server class syntax

我正在尝试将我的脚本转换为类,因为我每次都会使用connect方法, 我想将它放在构造函数中,然后在其他函数中调用它。 我是Python的新类,这是一个

from datetime import date
import pymssql
import sys

class PHQuery:
    def __init__(self):
        self.conn = self.conn()


    def get_stock_by_sku(self, sku):
        if self.conn["code"] < 0:
            return {"code":-1,"error":conn["error"]}
        cursor = self.conn.cursor(as_dict=True)
        try:
            cursor.execute('''
                SELECT NUMBER, UNITS, LOW, UNCOST, PRICE1, ONORDER 
                FROM STOCK 
                WHERE NUMBER=%s''', sku)
            return {"code":1,"data":cursor.fetchone()}
        except Exception as e:
            return {"code":-2,"error":e}

    def conn(self):
        try:
            conn = pymssql.connect(server='server', user='user', password='pwd', database='db', timeout=0, login_timeout=60, charset='UTF-8', as_dict=False, port='1433')
            return {"code":1,"data":conn}
        except Exception as e:
            return {"code":-1,"error":e}

输出错误:

文件“test.py”,第3行,in     print testObject.get_stock_by_sku('BK31') TypeError:unbound方法get_stock_by_sku()必须使用PHQuery实例作为第一个参数调用(改为使用str实例)

这是对方法的调用

from query import PHQuery
testObject = PHQuery    
print testObject.get_stock_by_sku('BK31')

这是我的目标

data = {"stock_id" : "12345"}
qobject = PHQuery()
qobject.get_stock_by_sku(data["stock_id"])

并返回我的脚本返回的相同数据: 下面的脚本工作得很好,我只需要把它变成一个类。

谢谢你提前。

工作代码:

import time
from datetime import date
import pymssql
import sys

def conn():
    try:
        conn = pymssql.connect(server='', user='', password='', database='', timeout=0, login_timeout=60, charset='UTF-8', as_dict=False, port='1433')
        return {"code":1,"data":conn}
    except Exception as e:
        return {"code":-1,"error":e}
conn = conn()


def get_stock_by_sku(conn,sku):
    """ Returns stock information when passing a sku"""
    if conn["code"] < 0:
        return {"code":-1,"error":conn["error"]}
    cursor = conn["data"].cursor(as_dict=True)
    try:
        cursor.execute('''
            SELECT NUMBER, UNITS, LOW, UNCOST, PRICE1, ONORDER 
            FROM STOCK 
            WHERE NUMBER=%s''', sku)
        return {"code":1,"data":cursor.fetchone()}
    except Exception as e:
        return {"code":-2,"error":e}

0 个答案:

没有答案