【发布时间】: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