如何在不使用循环的情况下使用列名显示行?

2024-09-25 02:37:42 发布

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

import mysql.connector

myDB = pymysql.connect(
  host="localhost",
  user="exampleuser",
  password="examplepassword",
  database="exampledb"
)

myCursor = myDB.cursor(dictionary=True)
msg = "something"
SQL = "SELECT * FROM `example` WHERE `example`='" + msg + "'"
myCursor.execute(SQL)
myResult = myCursor.fetchall()

for row in myResult:
  print(row["example1"])

我怎样才能这样做:

row = someFunctionThatDoesWhatINeed(myResult)

print(row["example1"])

因此,我的意思是,我不想使用for循环来使用列名显示行的值

编辑:

就像在PHP中一样:

while ($row = mysqli_fetch_assoc($result)) {
  echo $row["example1"];
}

或:

$row = mysqli_fetch_assoc($result);
echo $row["example1"];

我知道这些循环用于多行。但是,它将只返回单行。所以,不用于循环,对吗

此外,我永远不会使用fetchone()而不是fetchall()。不要向我推荐包含fetchone()的示例

重要编辑:

当我没有得到多行时,我不能不必要地使用任何循环。所以,不要建议循环

名单如下:

[{'id': 1, 'name': 'example.tld', 'domainId': '12345678_DOMAIN_tld-example', 'nsgroupId': 1, 'resellerId': 0, 'registrarId': 1, 'ownerHandle': '12242342432ABC', 'techHandle': '12242342432ABC', 'adminHandle': '12242342432ABC', 'billingHandle': '12242342432ABC', 'dnssec': 'unsigned', 'updatedDate': datetime.datetime(2020, 11, 1, 1, 11, 39), 'creationDate': datetime.datetime(2017, 11, 1, 1, 11, 39), 'expirationDate': datetime.datetime(2021, 11, 1, 1, 11, 39)}]

我想将它们显示为:

Domain Name: row[name] # Domain Name: example.tld

Tags: 编辑forsqldatetimeexamplemsgrowexample1
2条回答

我们不知道您的查询返回了什么数据,但假设有3个字段—id、名称和地址

也许像这样的事情可能会奏效

res =['Name Address']
res.extend([f'{name} {address}' for id, name, address in myResult])

print(res)
print('\n'.join(res))

这样做可能会奏效——第一部分是字段名

fields = map(lambda x:x[0], cursor.description)
result = [dict(zip(fields,row))   for row in cursor.fetchall()]

这是我的方法:

first convert mysql table into a pandas dataframe.

    import mysql.connector as sql

    import pandas as pd

    db_connection = sql.connect(host='hostname', database='db_name', user='username', password='password')

    db_cursor = db_connection.cursor()

    db_cursor.execute('SELECT * FROM table_name')

    table_rows = db_cursor.fetchall()

    df = pd.DataFrame(table_rows)

then display the rows using df.iterrows or df.itertuples

相关问题 更多 >