Dbms Exp 9
Dbms Exp 9
Ex.No.9
Open Database Connectivity
Aim
To establish connection between SQL database and python using ODBC(Open Database Connection).
Definition:
ODBC provides a standard way for programmers to create, access and manage databases regardless
of the type of database or the platform which it is running.
ODBC is a low-level, high-performance interface that is designs specifically for relational data
stores. It aligns with the ISO/IEC for database APIs.
ODBC accomplishes DBMS independence by using an ODBC driver as a translation layer between
the application and the DBMS. Users simply add database drivers to link the application to their
choice of DBMS.
STEPS:-
STEP1:Install Required Libraries
Collecting mysql-connector-python
Downloading mysql_connector_python-8.4.0-cp310-cp310-manylinux_2_17_x86_64.whl (19.4 MB)
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ 19.4/19.4 MB 65.6 MB/s eta 0:00:00
ysql-connector-python
Successfully installed mysql-connector-python-8.4.0
import mysql.connector
mydb = mysql.connector.connect(
mycursor = mydb.cursor()
Show Database
mycursor.execute("SHOW DATABASES")
for db in mycursor:
print(db)
('information_schema',)
('sql12712200',)
STEP5:Create a Table
create_table_query = """
CREATE TABLE IF NOT EXISTS users (
id INT AUTO_INCREMENT PRIMARY KEY,
username VARCHAR(50) NOT NULL,
email VARCHAR(100) NOT NULL
)
"""
mycursor.execute(create_table_query)
STEP6:Insert Data
user_data = [
("john_doe", "[email protected]"),
("jane_smith", "[email protected]"),
("alice", "[email protected]")
]
mycursor.executemany(insert_query, user_data)
mydb.commit()
select_query = """
SELECT * FROM users
"""
mycursor.execute(select_query)
users = mycursor.fetchall()
STEP8:Update Data
new_email = "[email protected]"
username_to_update = "john_doe"
STEP9:Show data
select_query = """
SELECT * FROM users
"""
mycursor.execute(select_query)
users = mycursor.fetchall()
STEP10:Delete Data
delete_query = """
DELETE FROM users WHERE username = %s
username_to_delete = "alice"
mycursor.execute(delete_query, (username_to_delete,))
mydb.commit()
STEP11:Show data
select_query = """
SELECT * FROM users
"""
mycursor.execute(select_query)
users = mycursor.fetchall()
STEP12:Close Connection
Result:
Thus, connection between SQL database and python are executed and verified successfully.