使用pyodbc的python类。多行错误

时间:2017-02-10 22:16:06

标签: python pyodbc

这段代码打印出一行预期的数据。它在第二行打印出“无”,我想要解释,但这不是主要问题

rows = cursor.fetchone()
for row in rows:
    cur = SHIPMENT_BO(row.SHIPMENT_NUM, row.SHIPMENT_ID, row.ORIGIN_BRANCH_CODE, row.DEST_BRANCH_CODE)
    print(cur.PrintShipment())

此代码仅返回函数中的第一个print语句,但不返回任何数据。

rows = cursor.fetchall()
for row in rows:
    cur = SHIPMENT_BO(row.SHIPMENT_NUM, row.SHIPMENT_ID, row.ORIGIN_BRANCH_CODE, row.DEST_BRANCH_CODE)
    print(cur.PrintShipment())

以下是我在上面调用的课程

class SHIPMENT_BO:

    def __init__(self, shipNo, shipId, origBranch, destBranch):
        self.__shipmentNo = shipNo
        self.__shipmentID = shipId
        self.__originBranch = origBranch
        self.__destinationBranch = destBranch


    def PrintShipment(self):
        print("Shipment No, Shipment ID, Origin Branch, Destination Branch")
        print(self.__shipmentNo + " " + str(self.__shipmentID) + " " + self.__originBranch + " " + self.__destinationBranch)

如果我直接打印出货号,它会按预期打印数百万行

rows = cursor.fetchall()
for row in rows:
    print(row.SHIPMENT_NUM)
    #cur = SHIPMENT_BO(row.SHIPMENT_NUM, row.SHIPMENT_ID, row.ORIGIN_BRANCH_CODE, row.DEST_BRANCH_CODE)
    #print(cur.PrintShipment())

我的第一个问题是为什么代码和类适用于一行但不适用于多行?我的第二个问题是为什么在一行代码后得到“无”打印?最后这段代码根本不起作用(没有打印语句执行),当然你至少会得到你在光标中选择的那一行。

rows = cursor.fetchone()
for row in rows:
    cur = SHIPMENT_BO(row.SHIPMENT_NUM, row.SHIPMENT_ID, row.ORIGIN_BRANCH_CODE, row.DEST_BRANCH_CODE)
    print(cur.PrintShipment())

1 个答案:

答案 0 :(得分:1)

re:fetchone()与fetchall()

使用......

rows = cursor.fetchone()
for row in rows:

...看起来你希望pyodbc的fetchone()方法返回一个包含单个元组的列表,但是它没有。它返回一个pyodbc.Row对象。当您遍历该对象时,您实际上正在迭代该行的列值

sql = """\
SELECT 'foo' AS col1, 42 AS col2
"""
rows = cursor.execute(sql).fetchone()
for row in rows:
    print(row)

将打印

foo
42

另一方面,fetchall()会返回一个列表(pyodbc.Row个对象),所以它的行为更像你期望的

sql = """\
SELECT 'foo' AS col1, 42 AS col2
UNION ALL
SELECT 'bar' AS col1, 123 AS col2
"""
rows = cursor.execute(sql).fetchall()
for row in rows:
    print(row)

将打印

('foo', 42)
('bar', 123)

重新:每行后打印None

当你这样做时

print(cur.PrintShipment())

您调用PrintShipment方法,其中包含自己的print()函数调用,以显示列标题和列数据。然后在PrintShipment方法返回后,print - PrintShipment方法的返回值,即None,因为它不是return包含None声明。为了避免打印假的cur.PrintShipment() # not wrapped in a print() function 值,只需调用方法本身:

portaudio