Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import mysql.connector
- class Connection:
- def __init__(self, host, database, user, passwd):
- self.host = host
- self.database = database
- self.user = user
- self.passwd = passwd
- self.conn = None
- self.connect()
- def connect(self):
- try:
- self.conn = mysql.connector.connect(host=self.host,
- database=self.database,
- user=self.user,
- passwd=self.passwd)
- except:
- print("Error Connecting to Database.")
- exit()
- def insert_data(self, query):
- try:
- cursor = self.conn.cursor()
- cursor.execute(query)
- except:
- print("Error inserting data.")
- def retrieve_data(self, query):
- try:
- cursor = self.conn.cursor()
- cursor.execute(query)
- result = cursor.fetchall()
- return result
- except:
- return (["Error retrieving data"])
- mydb = Connection('localhost', 'sakila', 'root', 'passw0rd')
- # Insert Data
- query = "INSERT INTO actor ..."
- mydb.insert_data(query)
- # Retrieve Data
- query = "SELECT * FROM actor"
- data = mydb.retrieve_data(query)
- # Display retrieved data
- for row in data:
- print(row)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement