【问题标题】:How can I display rows using column names without using a loop?如何在不使用循环的情况下使用列名显示行?
【发布时间】:2021-06-05 00:21:19
【问题描述】:
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"];

我知道这些循环用于多行。但是,它只会返回单行。所以,不要使用 for 循环,对吧?

另外,我永远不会使用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

【问题讨论】:

  • for 循环有什么问题?这是做你想做的事情的最简单、最高效(也是纯 Python)的方法之一。
  • @User12692182,我的意思是,当我在两者之间使用不同的 mysql 连接时,我不能每次都使用它们.. 不必要的内存使用
  • 是什么让您认为使用循环会导致不必要的内存使用?处理时间可能但不确定内存使用情况。
  • @norie 我什至使用返回的row[example]s 运行 mysql 查询。那么,在循环中这样做不是很好吗?
  • 如果您希望只收到一行,为什么不使用myResult = myCursor.fetchone()

标签: python python-3.x mysql-python


【解决方案1】:

我们不知道您的查询返回了哪些数据,但假设有 3 个字段 - id、name 和 address。

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

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()]

【讨论】:

  • 我有大约 8 个字段......就像你假设的那样。一些个人数据,但不是密码/用户名
  • 我发布的代码非常简单 - 将 id、name、address 替换为您要显示的字段。
  • 不是:for id, name, address in myResult 一个循环吗?我要求没有任何循环的代码。
  • 如果您将列表理解视为一个循环,那么我恐怕无法看到不循环如何做到这一点。
【解决方案2】:

这是我的方法:

首先将 mysql 表转换为 pandas 数据框。

    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)

然后使用df.iterrowsdf.itertuples 显示行

【讨论】:

  • 有什么办法不用额外的imports?
猜你喜欢
  • 2012-02-06
  • 1970-01-01
  • 2017-09-05
  • 1970-01-01
  • 2011-02-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-02-27
相关资源
最近更新 更多