Java interacts with databases primarily through the Java Database Connectivity (JDBC) API. JDBC is a standard API that allows Java applications to connect to multiple types of databases, execute SQL queries, and manage the results. By using JDBC, developers can establish a connection to a database, execute SQL commands, and retrieve data in a Java-friendly way.
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
public class DatabaseExample {
public static void main(String[] args) {
Connection connection = null;
Statement statement = null;
ResultSet resultSet = null;
try {
// Load database driver
Class.forName("com.mysql.cj.jdbc.Driver");
// Establish connection
connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/mydatabase", "username", "password");
// Create a statement
statement = connection.createStatement();
// Execute a query
resultSet = statement.executeQuery("SELECT * FROM users");
// Process the results
while (resultSet.next()) {
System.out.println("User ID: " + resultSet.getInt("id"));
System.out.println("Username: " + resultSet.getString("username"));
}
} catch (Exception e) {
e.printStackTrace();
} finally {
// Clean up
try {
if (resultSet != null) resultSet.close();
if (statement != null) statement.close();
if (connection != null) connection.close();
} 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?