Advertisement
Guest User

Untitled

a guest
Jul 18th, 2019
172
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 2.03 KB | None | 0 0
  1. import mysql.connector
  2. from mysql.connector import Error
  3.  
  4. def connect_SQL_EMC_database():
  5.     try:
  6.        #Connecting to the database
  7.        mySQLconnection = mysql.connector.connect(host='sql9.freesqldatabase.com',
  8.                                  database='sql9298674',
  9.                                  user='sql9298674',
  10.                                  password='KR5i4m6mya')
  11.      
  12.  
  13.        sql_select_data = "select * from EMC_data" #to fetch all rows from the database
  14.        data_cursor = mySQLconnection.cursor()  #Creating a cursor to point to all entries in the database
  15.        data_cursor.execute(sql_select_data)   #returns a ResultSet object which contains all the rows
  16.        data_records = data_cursor.fetchall()
  17.  
  18.        sql_select_regions = "select * from EMC_regions" #to fetch all rows from the database
  19.        region_cursor = mySQLconnection.cursor()  #Creating a cursor to point to all entries in the database
  20.        region_cursor.execute(sql_select_regions)   #returns a ResultSet object which contains all the rows
  21.        region_records = region_cursor.fetchall()
  22.  
  23.        print("Total number of rows in EMC_data is - ", data_cursor.rowcount)
  24.        print ("Printing each row's column values ")
  25.        for row in data_records:
  26.            print("CUST_ID = ", row[0], )
  27.            print("DATE = ", row[1])
  28.            print("ORDER_QTY  = ", row[2])
  29.            print("PRICE_USD = ", row[3])
  30.            print("Region_CODE  = ", row[4], "\n")
  31.        data_cursor.close()
  32.  
  33.        print("Total number of rows in EMC_regions is - ", region_cursor.rowcount)
  34.        print ("Printing each row's column values ")
  35.        for row in region_records:
  36.            print("REGION = ", row[0], )
  37.            print("Region_CODE  = ", row[1], "\n")
  38.        region_cursor.close()
  39.  
  40.        
  41.     except Error as e :
  42.         print ("Error while connecting to MySQL", e)
  43.     finally:
  44.         #closing database connection.
  45.         if(mySQLconnection .is_connected()):
  46.             connection.close()
  47.             print("MySQL connection is closed")
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement