0% found this document useful (0 votes)
10 views5 pages

Python MySQL Connectivity Examples

The document outlines several exercises focused on MySQL database connectivity using Python. It includes creating a database and table, inserting records, displaying data, updating employee names, and deleting records. Each exercise provides a specific aim and corresponding Python code to achieve the tasks.

Uploaded by

orewairfan05
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
10 views5 pages

Python MySQL Connectivity Examples

The document outlines several exercises focused on MySQL database connectivity using Python. It includes creating a database and table, inserting records, displaying data, updating employee names, and deleting records. Each exercise provides a specific aim and corresponding Python code to achieve the tasks.

Uploaded by

orewairfan05
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

SQL Database Connectivity Programs

[Link].21

Aim:

To Write a MySQL connectivity program in Python to

o Create a database school


o Create a table students with the specifications – ROLLNO integer, STNAME
character(10) in MySQL and perform the following operations:
 Insert two records in it
 Display the contents of the table

Program:

import [Link]

mycon=[Link](host='localhost',user='root',passwd='root12345')

cursor=[Link]()

st="use school;"

[Link](st)

st3="create table student_details(Roll_no integer,Student_Name varchar(10));"

[Link](st3)

st4="insert into student_details values({},'{}');".format(1,'Anirudh')

[Link](st4)

[Link]()

st5="insert into student_details values({},'{}');".format(2,'Madhan')

[Link](st5)

st6="select * from student_details;"

[Link](st6)

data=[Link]()

for row in data:


print(row)

OUTPUT

Result:

[Link].22

Aim:

2. Perform all the operations with reference to table Employee through MySQL-Python
connectivity.

i)Write a python program to insert 5 records in Employee table. Take these 5 records as an input from
the user (One record at a time). Note the following to establish connectivity between Python and
MySQL: Username is root Password is 12345 The table exists in a MySQL database named company.
The table has five attributes (Emp_ID, Emp_Name, DOJ, Gender, Salary)

ii) Update name of employee in Employee table whose employee id is ‘E1001’ (Take name as an
input from the user).

[Link].23

AIM:

To Write a python program that display first 8 rows fetched from student table of MySQl database
student_dbl

Program:

import [Link]
mycon=[Link](host='localhost',user='root'

,passwd='root12345')

cursor=[Link]()

st="use school;"

[Link](st)

[Link]()

st="select * from student_dbl;"

[Link](st)

data=[Link](8)

for row in data:

print(row)

OUTPUT
(11, 'ATHANG', 12, 'A', 'MALE', 90)

(12, 'ATHARVA', 12, 'B', 'MALE', 80)

(13, 'ANJALI', 12, 'C', 'FEMALE', 78)

(14, 'MEENA', 12, 'C', 'FEMALE', 79)

(15, 'MEENAKSHI', 12, 'B', 'FEMALE', 53)

(16, 'SUSHIL', 12, 'B', 'MALE', 40)

(17, 'SUMEDH', 12, 'A', 'MALE', 69)

(18, 'LUMBINI', 12, 'A', 'FEMALE', 77)


[Link].24

AIM:

Write a python database connectivity program that deletes record from student table of database that
have name = Meena

Program:
import [Link]

mycon=[Link](host='localhost',user='root',passwd='root12345')

cursor=[Link]()

st1="use school;"

[Link](st1)

st2="delete from student_dbl where NAME='{}';".format('MEENA')

[Link](st2)

[Link]()

st3="select * from student_dbl;"

[Link](st3)

[Link]()

data=[Link]()

for row in data:

print(row)

[Link]()

OUTPUT
(11, 'ATHANG', 12, 'A', 'MALE', 90)
(12, 'ATHARVA', 12, 'B', 'MALE', 80)
(13, 'ANJALI', 12, 'C', 'FEMALE', 78)
(15, 'MEENAKSHI', 12, 'B', 'FEMALE', 53)
(16, 'SUSHIL', 12, 'B', 'MALE', 40)
(17, 'SUMEDH', 12, 'A', 'MALE', 69)
(18, 'LUMBINI', 12, 'A', 'FEMALE', 77)
(19, 'LOKESH', 12, 'B', 'MALE', 88)
(20, 'SUJATA', 12, 'A', 'FEMALE', 98)

Common questions

Powered by AI

User input is incorporated into SQL commands within Python using Python's string formatting methods. In the case of record insertion into the Employee table, user inputs are formatted into the SQL insert statement using the `format()` function, which helps in dynamically constructing the query string with user-provided data. This approach, while demonstrating the basic idea, is not the safest practice as it can lead to SQL injection vulnerabilities. Normally, it's recommended to use parameterized queries which libraries like `mysql.connector` support .

The `commit()` method is essential for ensuring that all modifications made to a database through SQL operations are saved permanently. In transactional databases like MySQL, changes are not automatically committed, allowing for rollback in case of errors or incomplete changes. By calling `mycon.commit()` after operations such as INSERT, UPDATE, or DELETE, the script ensures these changes are finalized and visible to other database users or subsequent operations. This function is vital in maintaining data integrity and consistency, particularly in applications requiring multiple changes in a single transaction .

The Python programs achieve MySQL database connectivity by using the `mysql.connector` module. They connect to the MySQL server by specifying the host ('localhost'), user (e.g., 'root'), and password (e.g., 'root12345'). Once the connection is established through `mycon=mysql.connector.connect()`, a cursor object is created to execute SQL statements. Various SQL operations like creating a database and tables, inserting records, selecting rows, and deleting specific records are done using cursor methods such as `execute()`, `fetchall()`, and `fetchmany()`. Each operation is followed by `mycon.commit()` to apply the changes permanently in the database .

While the provided examples do not explicitly show exception handling, Python handles exceptions in database operations by using try-except blocks to catch and manage potential errors that may arise during connection or SQL execution. In MySQL connectivity, exceptions such as `mysql.connector.errors.InterfaceError` and `mysql.connector.errors.ProgrammingError` can be caught to handle specific scenarios like connection failures or incorrect SQL syntax. Proper error handling ensures that database applications can respond gracefully to unforeseen issues, logging errors for debugging and implementing fallback logic or user notifications when operations cannot be completed successfully .

To update a record in MySQL using Python, first, establish a database connection using `mysql.connector.connect()`. Initiate a cursor object and execute a SQL UPDATE statement specifying the record to be updated and the new values. For instance, to update an employee's name where Emp_ID is 'E1001', capture the new name as user input and construct the SQL command to set the `Emp_Name`. Execute the statement with `cursor.execute()` and commit the changes to save them permanently in the database. This process ensures that specific database entries are correctly modified per the new data .

The `cursor` object acts as an interface for managing the execution of SQL commands and navigating through the results in Python. It is created by calling `mycon.cursor()` and is used to execute SQL statements such as `execute()`, retrieve data through `fetchall()` or `fetchmany()`, and navigate through recordsets. The cursor is essential for performing operations such as creating tables, inserting records, updating, deleting, and querying data in the database .

The use of the `fetchmany` function is beneficial for efficiently retrieving a specified number of rows, which can be essential for handling large datasets. By fetching only the first 8 rows from the student_dbl table, it reduces memory consumption and improves performance when the entire dataset is large and not all records are required at once. This approach is particularly useful for paginated queries or processing data in chunks .

The major security concern is the potential for SQL injection due to the use of Python's string formatting (`format()`) for query construction. This method directly inserts user inputs into SQL statements without proper validation or parameterization, making it vulnerable to malicious inputs that can alter the behavior of the SQL query. Using parameterized queries with placeholders and a safe API method to bind variables is the recommended approach to mitigate such risks .

The `mysql.connector` module enables cross-platform database application development in Python by providing a consistent API to connect to MySQL databases regardless of the underlying operating system. It abstracts many of the complexities involved in establishing a secure connection, executing SQL commands, and retrieving results. This allows developers to focus on application logic, ensuring the Python scripts work across different environments with little to no modification. This compatibility and abstraction support seamless integration and migration of database applications across various platforms .

The purpose of deleting a record from the MySQL table using Python is to remove specific entries that match given criteria, thus managing the dataset remaining in the table. The process involves establishing a connection to the MySQL database, creating a cursor object, and executing a DELETE SQL statement specifying the condition for deletion (in this case, `NAME='MEENA'`). After executing the delete operation with `cursor.execute()`, `mycon.commit()` is called to apply the changes. This deletes the record with the name 'Meena' from the student_dbl table, as shown by the updated dataset excluding the deleted row .

You might also like