Friday, 22 September 2017

How to create and use database connection ?


FOR MYSQL, USE MODULE pymysql
FOR ORACLE, USE MODULE cx_oracle

import pymysql

# Create connection to MySQL DB

def createConn():
    conn = pymysql.connect(host="10.238.207.56", user="root", passwd="Mypass@123", db="idmgt")
    return conn


# Method to fetch all records

def fetchRecords():
    conn = createConn()
    query = "select * from roles"
    cursor = conn.cursor()
    cursor.execute(query)
    return cursor.fetchall()


# Method to fetch record by ID

def fetchByRoleId(roleId):
    conn = createConn()
    cursor = conn.cursor()
    cursor.execute("""select * from roles where id=%d""" %(roleId))
    return cursor.fetchall()


# First statement : Call upper method to fetch records
rows = fetchRecords()

# Then, Iterate the records

for row in rows:
    for col in row:
        print(col)


No comments:

Post a Comment

Note: only a member of this blog may post a comment.