Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Assign query result to variable

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_table table. addr is of inet type.

When I assign the 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 proper way to get such thing?

like image 899
Jay Avatar asked Dec 17 '14 18:12

Jay


1 Answers

you can use the following steps for retrieving the 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()
like image 94
Mrityunjay Singh Avatar answered Sep 25 '22 16:09

Mrityunjay Singh