Python:只打印SQL查询结果的一个值

2024-04-28 19:38:19 发布

您现在位置:Python中文网/ 问答频道 /正文

from sqlalchemy import create_engine
engine = create_engine('mssql+pymssql://myusername:mypassword@127.0.0.1:1433/AQOA_Core')
connection = engine.connect()
result = connection.execute("""SELECT DISTINCT Distributor FROM Product""")
for row in result:
    print row[0]
connection.close()

上面的代码返回一个结果集:

FRANCETV
GAUMONT
M6SND
PATHE
STUDIOCANAL
TF1
WARNER

如果只打印一个值而不更改查询,该怎么办?

尝试了print row[0][1]print row[0:1]这只是尝试打印第一个值FRANCETV

基本上,我希望能够在不更改查询的情况下分别打印结果集中的每个值。


Tags: fromimportsqlalchemycreateresultconnectionenginerow
2条回答

如果您查看pymssql文档,就会看到cursor对象有一个^{}方法。

with engine.connect() as connection:
    cursor = connection.cursor()
    cursor.execute("""SELECT DISTINCT Distributor FROM Product""")
    first_row = cursor.fetchone()
    print first_row

您可以尝试通过以下方式访问数据:

connection = engine.connect()
result = connection.execute("""SELECT DISTINCT Distributor FROM Product""")
result_list = result.fetchall()  
result_list[0][0]
connection.close()

相关问题 更多 >