Assigning a query result to a variable

I have the 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 in the table list_table. addrhas type inet.

When I assign a query to a variable and print its result, I get None:

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

What is the right way to get such a thing?

+4
source share
3 answers

you can use the following steps to retrieve data for a relational database using 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()
+7
source

You must use fetchone()or fetchall()to get lines from the cursor.

fetch.

- :

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

.

execute() the method prepares and performs an operation with the database and, according to the documentation:

The method returns None . If the request has been executed, return values ​​can be obtained using the fetch * () methods.

fetchone() is most convenient to use, since your query returns a single value, count:

print(cur.fetchone())
+3
source

Source: https://habr.com/ru/post/1568039/


All Articles