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?

Python SQL Connection Diagram: mysql-connector-python Flow

JDBC Java Database Connectivity Architecture Diagram

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:

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:

3. What are prepared statements in SQL?

Prepared Statements vs String Concatenation: Secure Parameter Binding Diagram

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:

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 Attack Illustration: Malicious Input Altering Query

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:

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:

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:

8. What are common mistakes when using SQL with programming languages?

SQL in Python/Java:

Prepared Statements:

SQL Injection:

General:

9. What are best practices for using SQL with programming languages?

Best Practices for SQL in Programming: Security, Performance Infographic

SQL in Python/Java:

Prepared Statements:

SQL Injection Prevention:

General: