Java Database Connectivity (JDBC) is an API for interacting with databases from applications written in the Java programming language. JDBC provides a universal way to access different database management systems (DBMS) and allows you to execute SQL queries, retrieve and update data.
Examples of use:
Use DriverManager to get a connection to a database. Make sure that you have the appropriate JDBC driver for your database.
String url = "jdbc:mysql://localhost:3306/database_name";
String user = "user";
String password = "password";
Connection connection = DriverManager.getConnection(url, user, password);
Use the Statement object to create SQL queries.
Statement statement = connection.createStatement();
String sqlQuery = "SELECT * FROM table";
Use the executeUpdate methods to execute queries that change data.
String updateQuery = "UPDATE table SET field = 'new value' WHERE condition";
int rowsAffected = statement.executeUpdate(updateQuery);
Use the executeQuery methods to execute SELECT queries and get the results.
ResultSet resultSet = statement.executeQuery(sqlQuery);
Use the next methods to iterate over the results and retrieve data.
while (resultSet.next()) {
int id = resultSet.getInt("id");
String name = resultSet.getString("name");
// Data processing
}
Important: Always close resources (connection, statement, resultSet) after use to avoid memory leaks. They can be closed using the close() method.