这段代码打印出一行预期的数据。它在第二行打印出"无",我也想对此进行解释,但这不是的主要问题
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())
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)
re:每行打印None
当你做
print(cur.PrintShipment())
您可以调用PrintShipment
方法,该方法包括自己的print()
函数调用,以显示列标题和列数据。然后,在PrintShipment
方法返回后,您就是print
,使用PrintShipment
方法的返回值,即None
,因为它不包括return
语句。为了避免打印伪造的None
值,只需调用方法本身:
cur.PrintShipment() # not wrapped in a print() function