DB connectivity
DB connectivity
Python supports connection with MYSQL (and other databases) to manage data in Database through
Python Interface. Python’s mysql.connector module provides programming support for establishing
connection with a MYSQL Database, perform database operations and execute queries.
2. Create a Connection Object - Python allows programs to access MySQL databases through
mysql.connector module. It’s connect() method is used to establish a connection between
MySQL and Python Program/Interface. It returns a MySQLConnection object if the connection
is established successfully. connect() method takes four parameters – host set to localhost,
user & passwd for username & password which should be the as set during MySQL installation
and an optional database parameter which should be set to the database name or skipped
when there is a need to create a database
Example
ConObj = sqlcon.connect(host=“localhost”, user=“root”, passwd=“root”, database=“ProdDB”)
if mycon:
print(mycon)
4. Execute Query
The execute() method of the cursor object is used to execute the SQL statements in Python.
The query is passed as a string.
CursorObj.execute(“query”)
Whenever any change is made to data in a relation, the changes should be made permanent
using the commit( ) method of the connection object.
ConObj.commit( )
Output
Connection established successfully
Database created…
2. CREATING A TABLE
Output
Student table created…
3. INSERT RECORD
Output
Student Record inserted…
4. DISPLAY ALL RECORDS
Output
Records in the Result Set 2
[(10010, 'Amar'), (10011, 'Jyoti')]
Display individual records
(10010, 'Amar')
(10011, 'Jyoti')
5. UPDATE DATA
Output
Updated data...
(10010, 'Amarjit')
(10011, 'Jyoti')
6. DELETING A RECORD
Output
Data after deleting the record...
(10011, 'Jyoti')