我使用下面的查询cur.execute("SELECT COUNT(addr) FROM list_table WHERE addr = '192.168.1.1'")来计算同一地址(192.168.1.1)出现在list_table表中的次数。addr是一种内联类型。
当我将查询赋值给一个变量并打印它的结果时,我得到了None
res = cur.execute("SELECT COUNT(addr) FROM list_table WHERE addr = '192.168.1.1'")
print res # None得到这样的东西的正确方式是什么?
发布于 2016-02-14 17:03:57
您可以使用以下步骤通过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()发布于 2014-12-18 03:01:22
您必须使用fetchone()或fetchall()从游标中获取行。
在您的例子中,大致是这样的:
res = cur.execute("SELECT COUNT(addr) FROM list_table WHERE addr = '192.168.1.1'")
row = cur.fetchone()
print(row)发布于 2014-12-18 03:11:41
只是更多的解释。
execute()方法准备并执行数据库操作,并根据文档:
方法返回None。如果执行了查询,则可以使用fetch*()方法检索返回值。
fetchone()是最方便使用的,因为您的查询返回单个值,即计数:
print(cur.fetchone())https://stackoverflow.com/questions/27532823
复制相似问题