Retrieve the records from mysql table

Previous
Next

Retrieving the records:

  • When we create cursor object, that will be empty.
  • Empty object fill with data when we execute any select query.
  • We can access the information from cursor object using functionality of cursor object.

Fetching one record:

import mysql.connector
class DB:
    con=None
    def main():
        try :
            DB.con = mysql.connector.connect(user='root',
                                    password='root',
                                    host='127.0.0.1',
                                    database='student')
            print("Connected...")
            cur = DB.con.cursor()

            query = "select * from account where no=103"            
            cur.execute(query)

            record = cur.fetchone()
            print("Details :")
            print(record)

            print("Accno :",record[0])
            print("Name :",record[1])
            print("Balance :",record[2])

        except Exception as e:
            print("Exception :",e)

        finally:
            if DB.con != None:
                DB.con.close()
                print("Connection closed..")

        return

DB.main()

Fetch all records:

import mysql.connector
class DB:
    con=None
    def main():
        try :
            DB.con = mysql.connector.connect(user='root',
                                    password='root',
                                    host='127.0.0.1',
                                    database='student')
            print("Connected...")
            cur = DB.con.cursor()

            query = "select * from account"            
            cur.execute(query)

            table = cur.fetchall()
            print("Records are :")
            for record in table :
                print(record)

        except Exception as e:
            print("Exception :",e)

        finally:
            if DB.con != None:
                DB.con.close()
                print("Connection closed..")

        return

DB.main()

Access individual fields of each record:

import mysql.connector
class DB:
    con=None
    def main():
        try :
            DB.con = mysql.connector.connect(user='root',
                                    password='root',
                                    host='127.0.0.1',
                                    database='student')
            print("Connected...")
            cur = DB.con.cursor()

            query = "select * from account"            
            cur.execute(query)

            table = cur.fetchall()
            print("Records are :")
            for record in table :
                for field in record:
                    print(field)

        except Exception as e:
            print("Exception :",e)

        finally:
            if DB.con != None:
                DB.con.close()
                print("Connection closed..")

        return

DB.main()
Previous
Next

Add Comment

Courses Enquiry Form