This guide describes the steps for Java Servlets to interact with databases: Establish a database connection Create a Statement Execute a query Process the result set Release resources Using the JDBC API sample code, developers can connect to the database, execute queries, and process the results.
Java Servlet is one of the most popular web development frameworks, which allows developers to create dynamic and interactive web app. Servlets can also interact with databases to store and retrieve data. The following is a guide on how to implement this feature:
JDBC (Java Database Connection) is a Java API that interacts with the database. The following is a code example of using JDBC to connect to the database:
import java.sql.*; public class DatabaseConnectionExample { public static void main(String[] args) { Connection conn = null; Statement stmt = null; ResultSet rs = null; // 数据库连接信息 String url = "jdbc:mysql://localhost:3306/test"; String user = "root"; String password = "password"; try { // 建立数据库连接 conn = DriverManager.getConnection(url, user, password); // 创建Statement stmt = conn.createStatement(); // 执行查询 rs = stmt.executeQuery("SELECT * FROM users"); // 遍历结果集 while (rs.next()) { int id = rs.getInt("id"); String name = rs.getString("name"); // 打印结果 System.out.println("ID: " + id + ", Name: " + name); } } catch (SQLException e) { e.printStackTrace(); } finally { // 释放资源 try { if (rs != null) { rs.close(); } if (stmt != null) { stmt.close(); } if (conn != null) { conn.close(); } } catch (SQLException e) { e.printStackTrace(); } } } }
By following these steps and leveraging sample code, developers can easily implement interaction with databases in Java Servlet applications.
The above is the detailed content of How do Java Servlets interact with databases?. For more information, please follow other related articles on the PHP Chinese website!