SQL with Python & Java: Master Connectivity, Prepared Statements, SQL Injection Prevention with Examples
Table of Contents
- 1. How do you use SQL with Python and Java?
- 2. Examples of SQL in Python and Java
- 3. What are Prepared Statements?
- 4. Examples of Prepared Statements in Python and Java
- 5. What is SQL Injection and How to Prevent It?
- 6. Examples of Preventing SQL Injection
- 7. Comprehensive Example with Prepared Statements and Prevention
- 8. Common Mistakes
- 9. Best Practices
1. How do you use SQL with Python and Java?


SQL can be integrated with Python and Java to interact with databases programmatically, enabling dynamic queries, data manipulation, and application logic.
Python: Common libraries include mysql-connector-python (MySQL), psycopg2 (PostgreSQL), pyodbc (SQL Server), and sqlite3 (SQLite, built-in).
Java: Uses JDBC (Java Database Connectivity) with drivers for MySQL, PostgreSQL, SQL Server, Oracle, etc.
Key Steps:
- Connect to the database.
- Execute SQL queries (
SELECT,INSERT, etc.). - Handle results or errors.
- Close connections.
Use Case: Building a web application to display or update employee data.
2. Can you give an example of SQL in Python and Java?
Python Example (using mysql-connector-python):
# Python: Using mysql-connector-python for MySQL
import mysql.connector
from mysql.connector import Error try: # Connect to database connection = mysql.connector.connect( host="localhost", user="root", password="password123", database="company_db" ) # Create cursor cursor = connection.cursor() # Create table cursor.execute(""" CREATE TABLE IF NOT EXISTS Employees ( EmployeeID INT PRIMARY KEY, FirstName VARCHAR(50), Salary DECIMAL(10, 2), DepartmentID INT ) """) # Insert data cursor.execute(""" INSERT INTO Employees (EmployeeID, FirstName, Salary, DepartmentID) VALUES (1, 'John', 60000.00, 1) """) # Query data cursor.execute("SELECT * FROM Employees WHERE Salary > 55000.00") results = cursor.fetchall() # Display results for row in results: print(f"ID: {row[0]}, Name: {row[1]}, Salary: {row[2]}, Dept: {row[3]}") # Commit changes connection.commit() except Error as e: print(f"Error: {e}") finally: if connection.is_connected(): cursor.close() connection.close() print("Connection closed") Java Example (using JDBC):
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement; public class SqlJavaExample { public static void main(String[] args) { String url = "jdbc:mysql://localhost:3306/company_db"; String user = "root"; String password = "password123"; try (Connection conn = DriverManager.getConnection(url, user, password)) { // Create statement Statement stmt = conn.createStatement(); // Create table stmt.executeUpdate(""" CREATE TABLE IF NOT EXISTS Employees ( EmployeeID INT PRIMARY KEY, FirstName VARCHAR(50), Salary DECIMAL(10, 2), DepartmentID INT ) """); // Insert data stmt.executeUpdate(""" INSERT INTO Employees (EmployeeID, FirstName, Salary, DepartmentID) VALUES (1, 'John', 60000.00, 1) """); // Query data ResultSet rs = stmt.executeQuery("SELECT * FROM Employees WHERE Salary > 55000.00"); // Process results while (rs.next()) { System.out.println("ID: " + rs.getInt("EmployeeID") + ", Name: " + rs.getString("FirstName") + ", Salary: " + rs.getDouble("Salary") + ", Dept: " + rs.getInt("DepartmentID")); } } catch (SQLException e) { System.err.println("SQL Error: " + e.getMessage()); } }
} Output (Python and Java):
ID: 1, Name: John, Salary: 60000.00, Dept: 1
Connection closed (Python) Note:
- Python: Uses
mysql.connectorto connect, execute SQL, and fetch results; includes error handling and connection cleanup. - Java: Uses JDBC with
DriverManagerfor connectivity; employs try-with-resources for automatic connection closure. - Assumes MySQL database
company_dband appropriate driver (e.g., MySQL Connector/J for Java). - Integrates prior SQL concepts (
CREATE TABLE,INSERT,SELECT).
3. What are prepared statements in SQL?

Prepared statements are precompiled SQL queries with placeholders for parameters, executed with specific values at runtime. They improve performance (by reusing query plans) and prevent SQL injection by separating SQL code from user input.
Syntax (Python): Use ? or %s placeholders with parameterized queries.
Syntax (Java): Use ? placeholders with PreparedStatement.
Benefits:
- Prevents SQL injection by escaping user input.
- Reuses query plans for repeated executions.
- Improves readability and maintainability.
4. Can you give an example of prepared statements in Python and Java?
Python Example:
import mysql.connector
from mysql.connector import Error try: connection = mysql.connector.connect( host="localhost", user="root", password="password123", database="company_db" ) cursor = connection.cursor(prepared=True) # Insert using prepared statement insert_query = """ INSERT INTO Employees (EmployeeID, FirstName, Salary, DepartmentID) VALUES (%s, %s, %s, %s) """ employee_data = (2, 'Jane', 55000.00, 2) cursor.execute(insert_query, employee_data) # Select using prepared statement select_query = "SELECT * FROM Employees WHERE Salary > %s AND DepartmentID = %s" params = (50000.00, 1) cursor.execute(select_query, params) results = cursor.fetchall() for row in results: print(f"ID: {row[0]}, Name: {row[1]}, Salary: {row[2]}, Dept: {row[3]}") connection.commit() except Error as e: print(f"Error: {e}") finally: if connection.is_connected(): cursor.close() connection.close() print("Connection closed") Java Example:
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException; public class PreparedStatementsJava { public static void main(String[] args) { String url = "jdbc:mysql://localhost:3306/company_db"; String user = "root"; String password = "password123"; try (Connection conn = DriverManager.getConnection(url, user, password)) { // Insert using prepared statement String insertQuery = """ INSERT INTO Employees (EmployeeID, FirstName, Salary, DepartmentID) VALUES (?, ?, ?, ?) """; PreparedStatement insertStmt = conn.prepareStatement(insertQuery); insertStmt.setInt(1, 2); insertStmt.setString(2, "Jane"); insertStmt.setDouble(3, 55000.00); insertStmt.setInt(4, 2); insertStmt.executeUpdate(); // Select using prepared statement String selectQuery = "SELECT * FROM Employees WHERE Salary > ? AND DepartmentID = ?"; PreparedStatement selectStmt = conn.prepareStatement(selectQuery); selectStmt.setDouble(1, 50000.00); selectStmt.setInt(2, 1); ResultSet rs = selectStmt.executeQuery(); while (rs.next()) { System.out.println("ID: " + rs.getInt("EmployeeID") + ", Name: " + rs.getString("FirstName") + ", Salary: " + rs.getDouble("Salary") + ", Dept: " + rs.getInt("DepartmentID")); } } catch (SQLException e) { System.err.println("SQL Error: " + e.getMessage()); } }
} Output (Python and Java):
ID: 1, Name: John, Salary: 60000.00, Dept: 1
Connection closed (Python) 5. What is SQL injection, and how do you prevent it?

SQL injection is a security vulnerability where attackers inject malicious SQL code into input fields, manipulating queries to access or modify unauthorized data.
Example of Vulnerability:
-- Unsafe query with user input
SELECT * FROM Employees WHERE FirstName = 'John' OR '1'='1'; This query, if constructed with raw user input, could return all rows.
Prevention:
- Use prepared statements to separate SQL code from user input.
- Sanitize and validate input data.
- Use parameterized queries or ORM frameworks (e.g., SQLAlchemy in Python, Hibernate in Java).
- Limit database user permissions (e.g., no
DROPorALTERaccess). - Avoid dynamic SQL with string concatenation.
6. Can you give an example of preventing SQL injection?
Python Example:
import mysql.connector
from mysql.connector import Error try: connection = mysql.connector.connect( host="localhost", user="root", password="password123", database="company_db" ) cursor = connection.cursor(prepared=True) # Unsafe query (vulnerable to SQL injection) user_input = "John' OR '1'='1" unsafe_query = f"SELECT * FROM Employees WHERE FirstName = '{user_input}'" # This would return all rows -- AVOID THIS! # Safe query with prepared statement safe_query = "SELECT * FROM Employees WHERE FirstName = %s" cursor.execute(safe_query, (user_input,)) results = cursor.fetchall() for row in results: print(f"ID: {row[0]}, Name: {row[1]}, Salary: {row[2]}, Dept: {row[3]}") connection.commit() except Error as e: print(f"Error: {e}") finally: if connection.is_connected(): cursor.close() connection.close() print("Connection closed") Java Example:
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException; public class SqlInjectionPreventionJava { public static void main(String[] args) { String url = "jdbc:mysql://localhost:3306/company_db"; String user = "root"; String password = "password123"; try (Connection conn = DriverManager.getConnection(url, user, password)) { // Unsafe query (vulnerable to SQL injection) String userInput = "John' OR '1'='1"; String unsafeQuery = "SELECT * FROM Employees WHERE FirstName = '" + userInput + "'"; // This would return all rows -- AVOID THIS! // Safe query with prepared statement String safeQuery = "SELECT * FROM Employees WHERE FirstName = ?"; PreparedStatement stmt = conn.prepareStatement(safeQuery); stmt.setString(1, userInput); ResultSet rs = stmt.executeQuery(); while (rs.next()) { System.out.println("ID: " + rs.getInt("EmployeeID") + ", Name: " + rs.getString("FirstName") + ", Salary: " + rs.getDouble("Salary") + ", Dept: " + rs.getInt("DepartmentID")); } } catch (SQLException e) { System.err.println("SQL Error: " + e.getMessage()); } }
} Output (Safe Query, Python and Java):
ID: 1, Name: John, Salary: 60000.00, Dept: 1
Connection closed (Python) Note:
- The unsafe query would return all rows due to the injected
OR '1'='1'. - The prepared statement treats
John' OR '1'='1'as a single string, safely querying only forFirstName='John'. - Integrates prior concepts (
SELECT,WHERE).
7. Can you provide a comprehensive example of SQL in Python and Java with prepared statements and SQL injection prevention?
Python Example:
import mysql.connector
from mysql.connector import Error try: # Connect to database connection = mysql.connector.connect( host="localhost", user="root", password="password123", database="company_db" ) cursor = connection.cursor(prepared=True) # Create table cursor.execute(""" CREATE TABLE IF NOT EXISTS Employees ( EmployeeID INT PRIMARY KEY, FirstName VARCHAR(50), Salary DECIMAL(10, 2), DepartmentID INT ) """) # Insert using prepared statement insert_query = """ INSERT INTO Employees (EmployeeID, FirstName, Salary, DepartmentID) VALUES (%s, %s, %s, %s) """ employees = [ (1, 'John', 60000.00, 1), (2, 'Jane', 55000.00, 2), (3, 'kristal', 65000.00, 1) ] cursor.executemany(insert_query, employees) # Query with prepared statement to prevent SQL injection user_input = "John' OR '1'='1" select_query = """ SELECT EmployeeID, FirstName, Salary FROM Employees WHERE FirstName = %s AND DepartmentID = %s """ params = (user_input, 1) cursor.execute(select_query, params) results = cursor.fetchall() for row in results: print(f"ID: {row[0]}, Name: {row[1]}, Salary: {row[2]}") # Update using prepared statement update_query = "UPDATE Employees SET Salary = %s WHERE EmployeeID = %s" cursor.execute(update_query, (62000.00, 1)) connection.commit() # Verify data cursor.execute("SELECT * FROM Employees") results = cursor.fetchall() for row in results: print(f"ID: {row[0]}, Name: {row[1]}, Salary: {row[2]}, Dept: {row[3]}") except Error as e: print(f"Error: {e}") if connection.is_connected(): connection.rollback() finally: if connection.is_connected(): cursor.close() connection.close() print("Connection closed") Java Example:
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException; public class ComprehensiveSqlJava { public static void main(String[] args) { String url = "jdbc:mysql://localhost:3306/company_db"; String user = "root"; String password = "password123"; try (Connection conn = DriverManager.getConnection(url, user, password)) { // Create table String createTable = """ CREATE TABLE IF NOT EXISTS Employees ( EmployeeID INT PRIMARY KEY, FirstName VARCHAR(50), Salary DECIMAL(10, 2), DepartmentID INT ) """; PreparedStatement createStmt = conn.prepareStatement(createTable); createStmt.executeUpdate(); // Insert using prepared statement String insertQuery = """ INSERT INTO Employees (EmployeeID, FirstName, Salary, DepartmentID) VALUES (?, ?, ?, ?) """; PreparedStatement insertStmt = conn.prepareStatement(insertQuery); Object[][] employees = { {1, "John", 60000.00, 1}, {2, "Jane", 55000.00, 2}, {3, "kristal", 65000.00, 1} }; for (Object[] emp : employees) { insertStmt.setInt(1, (Integer) emp[0]); insertStmt.setString(2, (String) emp[1]); insertStmt.setDouble(3, (Double) emp[2]); insertStmt.setInt(4, (Integer) emp[3]); insertStmt.executeUpdate(); } // Query with prepared statement to prevent SQL injection String userInput = "John' OR '1'='1"; String selectQuery = """ SELECT EmployeeID, FirstName, Salary FROM Employees WHERE FirstName = ? AND DepartmentID = ? """; PreparedStatement selectStmt = conn.prepareStatement(selectQuery); selectStmt.setString(1, userInput); selectStmt.setInt(2, 1); ResultSet rs = selectStmt.executeQuery(); while (rs.next()) { System.out.println("ID: " + rs.getInt("EmployeeID") + ", Name: " + rs.getString("FirstName") + ", Salary: " + rs.getDouble("Salary")); } // Update using prepared statement String updateQuery = "UPDATE Employees SET Salary = ? WHERE EmployeeID = ?"; PreparedStatement updateStmt = conn.prepareStatement(updateQuery); updateStmt.setDouble(1, 62000.00); updateStmt.setInt(2, 1); updateStmt.executeUpdate(); // Verify data rs = conn.createStatement().executeQuery("SELECT * FROM Employees"); while (rs.next()) { System.out.println("ID: " + rs.getInt("EmployeeID") + ", Name: " + rs.getString("FirstName") + ", Salary: " + rs.getDouble("Salary") + ", Dept: " + rs.getInt("DepartmentID")); } } catch (SQLException e) { System.err.println("SQL Error: " + e.getMessage()); } }
} Output (Python and Java):
ID: 1, Name: John, Salary: 60000.00
ID: 1, Name: John, Salary: 62000.00, Dept: 1
ID: 2, Name: Jane, Salary: 55000.00, Dept: 2
ID: 3, Name: kristal, Salary: 65000.00, Dept: 1
Connection closed (Python) Description:
- Python: Uses
mysql-connector-pythonwith prepared statements for safe insertion, querying, and updating; includes error handling and transaction rollback. - Java: Uses JDBC with
PreparedStatementfor secure operations; employs try-with-resources for connection management. - SQL Injection Prevention: Safely handles malicious input (
John' OR '1'='1'). - Integrates prior concepts (
CREATE TABLE,INSERT,SELECT,UPDATE).
8. What are common mistakes when using SQL with programming languages?
SQL in Python/Java:
- Not closing database connections, causing resource leaks.
- Using string concatenation for queries, enabling SQL injection.
- Ignoring error handling, leading to uncaught exceptions.
Prepared Statements:
- Not using prepared statements for user inputs, risking SQL injection.
- Incorrect parameter binding (e.g., wrong data types), causing errors.
- Reusing prepared statements without resetting parameters.
SQL Injection:
- Failing to validate user input before passing to queries.
- Assuming built-in escaping is sufficient without prepared statements.
- Granting excessive database permissions to application users.
General:
- Not optimizing queries, causing slow performance in applications.
- Hardcoding database credentials in code, risking exposure.
- Not using connection pooling for high-traffic applications.
9. What are best practices for using SQL with programming languages?

SQL in Python/Java:
- Use established libraries/drivers (e.g.,
mysql-connector-python,psycopg2, JDBC). - Implement connection pooling (e.g., Python:
mysql.connector.pooling, Java: HikariCP) for scalability. - Close connections explicitly or use try-with-resources (Java) or context managers (Python).
Prepared Statements:
- Always use prepared statements for queries with user input.
- Bind parameters with correct data types (e.g.,
setInt,setStringin Java). - Reuse prepared statements for repeated queries to improve performance.
SQL Injection Prevention:
- Never concatenate user input into SQL queries.
- Validate and sanitize input data (e.g., check for valid formats).
- Use least-privilege database accounts for applications (e.g.,
SELECT/INSERTonly).
General:
- Store credentials securely (e.g., environment variables, configuration files).
- Use
EXPLAINto optimize queries before integrating into code. - Log SQL errors for debugging (e.g., Python:
logging, Java: SLF4J). - Test with realistic data and edge cases (e.g.,
NULL, malicious inputs). - Monitor database performance (e.g., MySQL slow query log, PostgreSQL
pg_stat_statements).