[Go to site: main page, start]

0% found this document useful (0 votes)
69 views2 pages

Python SQL Connectivity Programs

Uploaded by

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

Python SQL Connectivity Programs

Uploaded by

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

Python–SQL Connectivity Programs (Class 12

CBSE)

Program 1: Connect to MySQL and Display Server Version


import [Link]

con = [Link](
host="localhost",
user="root",
password="yourpassword"
)

if con.is_connected():
print("Connected to MySQL Server")
cur = [Link]()
[Link]("SELECT VERSION()")
data = [Link]()
print("MySQL Server Version:", data[0])
[Link]()

Program 2: Create Database and Table


import [Link]

con = [Link](
host="localhost",
user="root",
password="yourpassword"
)

cur = [Link]()
[Link]("CREATE DATABASE IF NOT EXISTS school")
[Link]("USE school")
[Link]("CREATE TABLE IF NOT EXISTS student (roll INT, name VARCHAR(30))")
print("Database and Table created successfully!")
[Link]()

Program 3: Insert Records into Table


import [Link]

con = [Link](
host="localhost",
user="root",
password="yourpassword",
database="school"
)

cur = [Link]()
query = "INSERT INTO student VALUES (%s, %s)"
data = (1, "Amit")
[Link](query, data)
[Link]()
print("Record inserted successfully!")
[Link]()

Program 4: Retrieve and Display Records


import [Link]

con = [Link](
host="localhost",
user="root",
password="yourpassword",
database="school"
)

cur = [Link]()
[Link]("SELECT * FROM student")
rows = [Link]()

for r in rows:
print("Roll:", r[0], " Name:", r[1])

[Link]()

Program 5: Update and Delete Records


import [Link]

con = [Link](
host="localhost",
user="root",
password="yourpassword",
database="school"
)

cur = [Link]()

# Update example
[Link]("UPDATE student SET name='Rahul' WHERE roll=1")
[Link]()
print("Record updated!")

# Delete example
[Link]("DELETE FROM student WHERE roll=1")
[Link]()
print("Record deleted!")

[Link]()

Common questions

Powered by AI

The check 'if con.is_connected():' after attempting to connect to a MySQL server is significant as it verifies whether the connection has been successfully established. This conditional statement ensures that subsequent operations, like querying or data manipulation, are only executed if the connection to the server is stable, preventing potential errors and exceptions .

Data retrieval from a MySQL table using Python involves executing a SELECT query through a cursor object. After establishing a connection and setting the specific database, use 'cur.execute("SELECT * FROM student")' to run the query. Use 'cur.fetchall()' to fetch all records from the result set. Data can then be accessed iteratively using a for-loop, for example: 'for r in rows: print("Roll:", r[0], " Name:", r[1])' to display each record .

The commit function in Python's MySQL connectivity plays a crucial role in ensuring that changes made to the database are saved. When inserting, updating, or deleting records, executing 'con.commit()' applies all pending modifications from the current transaction. Transactions are crucial for data integrity, as they allow a series of operations to be completed fully or not at all, thus maintaining consistency .

A robust way to handle exceptions in Python during SQL operations is by using try-except blocks. For example, wrapping SQL commands within a try block allows specific exceptions, such as mysql.connector.Error, to be caught in the corresponding except block. This approach is important to prevent the application from crashing and to provide meaningful error messages or recovery actions, such as closing connections or rolling back transactions .

Updating a record in a MySQL table using Python is done with the UPDATE SQL command. For instance, execute 'cur.execute("UPDATE student SET name='Rahul' WHERE roll=1")' to change a student's name. Deleting a record uses the DELETE command: 'cur.execute("DELETE FROM student WHERE roll=1")'. Both operations must be followed by 'con.commit()' to save changes to the database .

To modify the given programs to list all databases on a MySQL server, execute a 'SHOW DATABASES' query after establishing a connection. Use a cursor to run 'cur.execute("SHOW DATABASES")' and fetch the results with 'databases = cur.fetchall()'. Iterate through 'databases' and print each to display all database names. This feature helps in managing and navigating multiple databases on a server .

To establish a connection to a MySQL server using Python, you need to use the 'mysql.connector.connect' method. You should specify parameters such as host, user, and password. For example: 'con = mysql.connector.connect(host="localhost", user="root", password="yourpassword")'. After executing this, you can check if the connection is successful using the 'is_connected()' method .

Directly using credentials within Python scripts for MySQL connections poses several security risks, including unauthorized access and data breaches. Hardcoding sensitive information such as usernames and passwords can lead to exposure if the script is shared or improperly secured. Storing credentials in environment variables or using secure vault services is recommended to mitigate these risks .

To create a database and table in MySQL using Python, first establish a connection to the MySQL server. Then, use a cursor object to execute SQL queries. For creating a database, use 'cur.execute("CREATE DATABASE IF NOT EXISTS school")', and to create a table, use 'cur.execute("CREATE TABLE IF NOT EXISTS student (roll INT, name VARCHAR(30))")'. Ensure to set the database to use with 'cur.execute("USE school")' .

To insert a record into a MySQL table using Python, you should connect to the MySQL server with the specific database set. Prepare an SQL INSERT query with placeholders, such as 'query = "INSERT INTO student VALUES (%s, %s)"'. Then, define the data to be inserted, e.g., 'data = (1, "Amit")', and execute the query with 'cur.execute(query, data)'. Commit the transaction with 'con.commit()' to finalize the insertion .

You might also like