Connecting with mysql from python:
connector:
- It is a package(module).
- Python library is not providing any module to connect with mysql database.
- connector module contains programs by which we connect with mysql database from python application.
connect():
- It is belongs to mysql.connector module.
- It takes input as
- connect(user, password, host, database)
- If input is valid, it returns connection object.
- If not valid, it raises exception.
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...")
except Exception as e:
print("Exception :",e)
finally:
if DB.con != None:
DB.con.close()
print("Closed...")
return
DB.main()
cursor():
- Dynamic method of Connection object
- Returns cursor object when we call.
- Cursor object providing execute() method
- execute() method can be used to execute any sql query in the database.
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 = "create table account(no int, name varchar(20), balance int)"
cur.execute(query)
print("Table created...")
except Exception as e:
print("Exception :",e)
finally:
if DB.con != None:
DB.con.close()
print("Connection closed..")
return
DB.main()