SQL injection prevention in Java involves using techniques that ensure user input is handled securely, preventing unauthorized access to the database. The most effective way to protect against SQL injection is to use prepared statements or parameterized queries, which allow you to safely insert user input without compromising your database.
Here's an example of how to implement prepared statements in Java:
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
public class SQLInjectionPreventionExample {
public static void main(String[] args) {
String url = "jdbc:mysql://localhost:3306/your_database";
String user = "your_username";
String password = "your_password";
try (Connection conn = DriverManager.getConnection(url, user, password)) {
String userInput = "exampleUser"; // Assuming this input comes from a user
String query = "SELECT * FROM users WHERE username = ?";
try (PreparedStatement pstmt = conn.prepareStatement(query)) {
pstmt.setString(1, userInput);
ResultSet rs = pstmt.executeQuery();
while (rs.next()) {
System.out.println("User ID: " + rs.getInt("id"));
System.out.println("Username: " + rs.getString("username"));
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
How do I avoid rehashing overhead with std::set in multithreaded code?
How do I find elements with custom comparators with std::set for embedded targets?
How do I erase elements while iterating with std::set for embedded targets?
How do I provide stable iteration order with std::unordered_map for large datasets?
How do I reserve capacity ahead of time with std::unordered_map for large datasets?
How do I erase elements while iterating with std::unordered_map in multithreaded code?
How do I provide stable iteration order with std::map for embedded targets?
How do I provide stable iteration order with std::map in multithreaded code?
How do I avoid rehashing overhead with std::map in performance-sensitive code?
How do I merge two containers efficiently with std::map for embedded targets?