Download as pdf or txt
Download as pdf or txt
You are on page 1of 2

1. What are CRUD operations, and how are they used in database management?

CRUD operations refer to the basic functionalities of a database management system, which are Create, Read,
Update, and Delete. These operations are used to manipulate data within a database.

 Create: Inserting new records or entities into the database.

 Read: Retrieving existing records from the database.

 Update: Modifying existing records in the database.

 Delete: Removing records from the database.

2. How can you perform CRUD operations in Python with MySQL?

In Python, you can perform CRUD operations with MySQL using libraries such as mysql-connector-python or
pymysql.
import mysql.connector

# Establish connection to MySQL database


mydb = mysql.connector.connect(
host="localhost",
user="username",
password="password",
database="dbname"
)

# Create cursor object


cursor = mydb.cursor()

# Create operation
cursor.execute("INSERT INTO tablename (column1, column2) VALUES (%s, %s)", ("value1", "value2"))
mydb.commit()

# Read operation
cursor.execute("SELECT * FROM tablename")
result = cursor.fetchall()

# Update operation
cursor.execute("UPDATE tablename SET column1 = %s WHERE column2 = %s", ("new_value",
"value_to_update"))
mydb.commit()

# Delete operation
cursor.execute("DELETE FROM tablename WHERE column = %s", ("value_to_delete",))
mydb.commit()

# Close cursor and connection


cursor.close()
mydb.close()
3. How do you handle errors while performing CRUD operations in Python with MySQL?

Error handling is crucial to ensure robustness in database operations. You can use try-except blocks to catch and
handle errors gracefully.
try:
# MySQL operations
except mysql.connector.Error as err:
print("MySQL Error:", err)

4. What are prepared statements, and why are they important in database operations?

Prepared statements are precompiled SQL statements that can be reused with different parameters. They help
prevent SQL injection attacks and improve performance by reducing the overhead of parsing SQL queries
repeatedly. In Python with MySQL, you can use prepared statements with placeholders (%s) to execute
parameterized queries.
cursor.execute("SELECT * FROM tablename WHERE column = %s", ("value",))

5. How can you ensure data integrity while performing CRUD operations in a multi-user environment?
Data integrity can be ensured by using transactions and appropriate locking mechanisms. In MySQL, transactions
allow you to perform a series of database operations as a single unit of work, ensuring that all operations
succeed or fail together. You can use transaction management functions like commit() and rollback() to maintain
data consistency.
try:
# Start transaction
mydb.start_transaction()

# CRUD operations

# Commit transaction
mydb.commit()

except mysql.connector.Error as err:


# Rollback transaction on error
mydb.rollback()
print("Transaction Error:", err)

You might also like