将查询结果赋值给变量

6
我有以下查询:cur.execute("SELECT COUNT(addr) FROM list_table WHERE addr = '192.168.1.1'"),用于计算在list_table表中相同地址(192.168.1.1)出现的次数。addr是inet类型。
当我将查询分配给一个变量并打印其结果时,我得到None:
res = cur.execute("SELECT COUNT(addr) FROM list_table WHERE addr = '192.168.1.1'")
print res # None

什么是获取此类事物的正确方法?

请阅读Python的标准数据库API - Burhan Khalid
4个回答

9
您可以使用以下步骤来使用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()

5

您需要使用 fetchone() 或者 fetchall() 方法从游标中获取行数据。

请查看可用的 fetch 方法

在您的情况下,可以尝试以下方法:

res = cur.execute("SELECT COUNT(addr) FROM list_table WHERE addr = '192.168.1.1'")
row = cur.fetchone()
print(row)

4

稍微解释一下。

execute() 方法准备并执行数据库操作,并根据文档说明:

该方法返回 None。如果执行了查询,则可以使用 fetch*() 方法检索返回的值。

fetchone() 最方便使用,因为您的查询返回单个值,即计数:

print(cur.fetchone())

0
你可以像这样做:
def ApplyQuery (query ,cursor):
   res = cur.execute(query)
   Return cur.fetchall()
   Sql1= “””SELECT COUNT(addr) FROM list_table WHERE addr = %d"””
   Rows=ApplyQuery(Sql1% 192.168.1.1,cursor)
   For r in rows:
      r1=r[0][0] #will give you first column in in first row and so on

请确保代码格式正确。你确定缩进是对的吗?https://www.w3schools.com/python/gloss_python_indentation.asp - AnonymousUser
1
我认为需要修复(缩进)。 - Grey

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接