Advertisement
Guest User

Untitled

a guest
Nov 20th, 2019
102
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.37 KB | None | 0 0
  1. import mysql.connector
  2.  
  3.  
  4. class Connection:
  5.     def __init__(self, host, database, user, passwd):
  6.         self.host = host
  7.         self.database = database
  8.         self.user = user
  9.         self.passwd = passwd
  10.         self.conn = None
  11.         self.connect()
  12.  
  13.     def connect(self):
  14.         try:
  15.             self.conn = mysql.connector.connect(host=self.host,
  16.                                                 database=self.database,
  17.                                                 user=self.user,
  18.                                                 passwd=self.passwd)
  19.         except:
  20.             print("Error Connecting to Database.")
  21.             exit()
  22.  
  23.     def insert_data(self, query):
  24.         try:
  25.             cursor = self.conn.cursor()
  26.             cursor.execute(query)
  27.         except:
  28.             print("Error inserting data.")
  29.  
  30.     def retrieve_data(self, query):
  31.         try:
  32.             cursor = self.conn.cursor()
  33.             cursor.execute(query)
  34.             result = cursor.fetchall()
  35.             return result
  36.         except:
  37.             return (["Error retrieving data"])
  38.  
  39.  
  40. mydb = Connection('localhost', 'sakila', 'root', 'passw0rd')
  41.  
  42. # Insert Data
  43. query = "INSERT INTO actor ..."
  44. mydb.insert_data(query)
  45.  
  46. # Retrieve Data
  47. query = "SELECT * FROM actor"
  48. data = mydb.retrieve_data(query)
  49.  
  50. # Display retrieved data
  51. for row in data:
  52.     print(row)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement