Python 将查询结果分配给变量
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/27532823/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Assign query result to variable
提问by Jay
I have following query cur.execute("SELECT COUNT(addr) FROM list_table WHERE addr = '192.168.1.1'")to count the number of times the same address (192.168.1.1) appears on list_tabletable. addris of inet type.
我有以下查询cur.execute("SELECT COUNT(addr) FROM list_table WHERE addr = '192.168.1.1'")来计算相同地址(192.168.1.1)出现在list_table表上的次数。addr是 inet 类型。
When I assign the query to a variable and print its result I get None:
当我将查询分配给一个变量并打印其结果时,我得到None:
res = cur.execute("SELECT COUNT(addr) FROM list_table WHERE addr = '192.168.1.1'")
print res # None
What is the proper way to get such thing?
获得这种东西的正确方法是什么?
回答by Jay
You have to use fetchone()or fetchall()to get the rows from the cursor.
您必须使用fetchone()或fetchall()从游标中获取行。
Take a look at the available fetchmethods.
看看可用的fetch方法。
In your case, something along the lines of:
在您的情况下,类似以下内容:
res = cur.execute("SELECT COUNT(addr) FROM list_table WHERE addr = '192.168.1.1'")
row = cur.fetchone()
print(row)
回答by alecxe
Just a little bit more explanation.
只是多一点解释。
execute()method prepares and executes a database operationand, according to the documentation:
execute()方法准备并执行数据库操作,并根据文档:
The method returns None. If a query was executed, the returned values can be retrieved using fetch*() methods.
该方法返回 None。如果执行了查询,则可以使用 fetch*() 方法检索返回值。
fetchone()is the most convenient to use since your query returns a single value, a count:
fetchone()是最方便使用的,因为您的查询返回一个值,一个计数:
print(cur.fetchone())
回答by Mrityunjay Singh
you can use the following steps for retrieving the data for a relational database using python:
您可以使用以下步骤使用 python 检索关系数据库的数据:
#!/usr/bin/python
# import the desired package
import MySQLdb
# Open database connection
db = MySQLdb.connect(hostaddress,user,password,db_name)
# prepare a cursor object using cursor() method
cursor = db.cursor()
# execute SQL query using execute() method.
cursor.execute("SELECT COUNT(addr) FROM list_table WHERE addr = '192.168.1.1'")
# Fetch a single row using fetchone() method and store the result in a variable.
data = cursor.fetchone()
#OR use fetchall() method to fetch multiple rows and store the result in a list variable.
data = cursor.fetchall()
print data
# disconnect from server
db.close()

