Database integration using Python is a common task in software development. Python offers several libraries and frameworks for working with databases. Here are some common interview questions for database integration using python:
Question 1: What is Python’s DB-API?
Answer: Python’s DB-API is a standard API that allows Python code to interact with relational databases. It provides a set of common methods to connect to a database, execute queries, fetch results, and handle transactions, among other operations.
Question 2: What are some popular Python libraries for database integration?
Answer: Some popular Python libraries for database integration are SQLite3, MySQLdb, psycopg2 for PostgreSQL, and SQLAlchemy as an Object Relational Mapper (ORM).
Question 3: How do you connect to a MySQL database using Python?
Answer: You can connect to a MySQL database using Python by installing the mysql-connector-python
package and using its connect
method to create a connection object.
import mysql.connector
conn = mysql.connector.connect(
host='localhost',
user='username',
password='password',
database='mydatabase'
)
Question 4: How do you execute SQL queries in Python?
Answer: SQL queries can be executed in Python by using the cursor.execute()
method after creating a cursor object from the connection object.
cursor = conn.cursor()
cursor.execute("SELECT * FROM table_name")
Question 5: How do you fetch data after executing a SQL query?
Answer: Data can be fetched using methods like cursor.fetchone()
for a single row or cursor.fetchall()
for all rows.
Question 6: What is SQLAlchemy?
Answer: SQLAlchemy is an Object-Relational Mapping (ORM) library for Python. It allows you to interact with your database using Python classes and objects instead of writing raw SQL queries.
Question 7: How do you handle transactions in Python’s DB-API?
Answer: Transactions can be handled using the commit()
and rollback()
methods on the connection object.
try:
cursor.execute("SQL QUERY")
conn.commit()
except:
conn.rollback()
Question 8: How do you use parameters in SQL queries?
Answer: Parameters can be used in SQL queries to prevent SQL injection. You can use placeholders like %s
in the query and pass the parameters as a tuple.
cursor.execute("INSERT INTO table_name (col1, col2) VALUES (%s, %s)", (val1, val2))
Question 9: What are the differences between SQLite and MySQL in Python?
Answer: SQLite is a lightweight, serverless, and self-contained SQL database engine, suitable for small projects or embedded applications. MySQL, on the other hand, is a fully-featured, enterprise-level database with support for multi-user access, ACID compliance, and networking.
Question 10: How can you close a database connection in Python?
Answer: Database connections should be closed using the close()
method on the connection object.
conn.close()