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.
cur.execute("SELECT COUNT(addr) FROM list_table WHERE addr = '192.168.1.1'")
list_table
addr
When I assign a 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 right way to get such a thing?
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()
You must use fetchone()or fetchall()to get lines from the cursor.
fetchone()
fetchall()
fetch.
fetch
- :
res = cur.execute("SELECT COUNT(addr) FROM list_table WHERE addr = '192.168.1.1'") row = cur.fetchone() print(row)
.
execute() the method prepares and performs an operation with the database and, according to the documentation:
execute()
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())
Source: https://habr.com/ru/post/1568039/More articles:Change function definition without assignment - pythonlast part of resource identifier in var - javascriptCombining two IEnumerable queries into one - c #Open safari developer tools for quick file access - safariAdd X-Auth-Token - C # HttpClient - c #Ленивая загрузка с помощью кеша гидратации - doctrine2The # to_s array in Ruby 2.1 broke my code - ruby | fooobar.comDataGrid - AlternatingRowBackground color, interfering with the color "IsMouseOver" - c #Requesting a list of objects with compound keys in EF - c #Refactoring a large application for ObjectFactory.GetInstance to use nested containers - structuremapAll Articles