Servlet 数据库访问


Servlet 数据库访问

概述

在web应用程序中,Servlet可以通过Java中的JDBC API访问数据库。Java数据库连接(JDBC)是一种标准的Java API,用于连接和执行与各种关系型数据库的交互。JDBC提供了与数据库进行连接、执行SQL语句、处理结果集等各种功能。

使用JDBC访问数据库

JDBC的核心是接口。Java应用程序可以通过这些接口与各种数据库交互。以下是连接到数据库并执行查询的典型JDBC代码:

import java.sql.*;

public class JDBCExample {
   // JDBC数据库连接URL,数据库名称为DBName
   static final String JDBC_DRIVER = "com.mysql.jdbc.Driver";  
   static final String DB_URL = "jdbc:mysql://localhost/DBName";

   // 数据库的用户名与密码,需要根据自己的设置
   static final String USER = "username";
   static final String PASS = "password";

   public static void main(String[] args) {
      Connection conn = null;
      Statement stmt = null;

      try{
         // 注册JDBC驱动
         Class.forName(JDBC_DRIVER);

         // 打开一个连接
         conn = DriverManager.getConnection(DB_URL, USER, PASS);

         // 执行查询
         stmt = conn.createStatement();
         String sql;
         sql = "SELECT id, name, age FROM Users";
         ResultSet rs = stmt.executeQuery(sql);

         // 处理结果集
         while(rs.next()){
            // 通过字段检索
            int id  = rs.getInt("id");
            String name = rs.getString("name");
            int age = rs.getInt("age");

            // 输出数据
            System.out.print("ID: " + id);
            System.out.print(", Name: " + name);
            System.out.print(", Age: " + age);
            System.out.print("\n");
         }
         // 关闭结果集,语句和连接
         rs.close();
         stmt.close();
         conn.close();
      }catch(SQLException se){
         // 处理JDBC错误
         se.printStackTrace();
      }catch(Exception e){
         // 处理Class.forName错误
         e.printStackTrace();
      }finally{
         // 关闭资源
         try{
            if(stmt!=null) stmt.close();
         }catch(SQLException se2){}
         try{
            if(conn!=null) conn.close();
         }catch(SQLException se){
            se.printStackTrace();
         }
      }
      System.out.println("Goodbye!");
   }
}

在Servlet中使用JDBC

使用JDBC在Servlet中连接数据库与在Java应用程序中连接数据库的方式基本相同。在Servlet中,我们通常需要在init()方法中初始化数据库连接,并在doGet()doPost()方法中执行查询操作。以下是在Servlet中使用JDBC的样例代码:

import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
import java.sql.*;

public class DBServlet extends HttpServlet {

   // JDBC数据库连接URL,数据库名称为DBName
   static final String JDBC_DRIVER = "com.mysql.jdbc.Driver";  
   static final String DB_URL = "jdbc:mysql://localhost/DBName";

   // 数据库的用户名与密码,需要根据自己的设置
   static final String USER = "username";
   static final String PASS = "password";

   public void init() throws ServletException {
      // JDBC 驱动程序初始化
      try {
         Class.forName(JDBC_DRIVER);
      } catch(Exception e) {
         e.printStackTrace();
      } 
   }

   public void doGet(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {
      
      Connection conn = null;
      Statement stmt = null;
      
      try {
         // 创建一个连接
         conn = DriverManager.getConnection(DB_URL, USER, PASS);

         // 执行查询
         stmt = conn.createStatement();
         String sql;
         sql = "SELECT id, name, age FROM Users";
         ResultSet rs = stmt.executeQuery(sql);

         // 发送HTML响应
         response.setContentType("text/html");
         PrintWriter out = response.getWriter();
         String title = "Database Result";
         out.println("<html><head><title>");
         out.println(title);
         out.println("</title></head><body><h1>");
         out.println(title);
         out.println("</h1><table border=\"1\"><tr><th>ID</th><th>Name</th><th>Age</th></tr>");

         // 处理结果集
         while(rs.next()){
            // 通过字段检索
            int id  = rs.getInt("id");
            String name = rs.getString("name");
            int age = rs.getInt("age");

            // 输出数据
            out.println("<tr><td>" + id + "</td><td>" + name + "</td><td>" + age + "</td></tr>");
         }
         out.println("</table></body></html>");

         // 关闭结果集,语句和连接
         rs.close();
         stmt.close();
         conn.close();
      } catch(SQLException se) {
         // 重写处理JDBC错误
         se.printStackTrace();
      } catch(Exception e) {
         // 处理不同的错误
         e.printStackTrace();
      } finally {
         // 关闭资源
         try {
            if(stmt!=null) stmt.close();
         } catch(SQLException se2) {
            // 重写处理JDBC错误
         }
         try {
            if(conn!=null) conn.close();
         } catch(SQLException se) {
            // 重写处理JDBC错误
            se.printStackTrace();
         }
      }
   }

   public void destroy() {
      // 什么也不做
   }
}

总结

在Servlet中使用JDBC访问数据库是一种常见的web应用程序技术。通过使用Java标准JDBC API,我们可以轻松地建立与各种关系型数据库的连接,并执行查询等各种操作。在Servlet中,我们可以在init()方法中初始化数据库连接,然后在doGet()doPost()方法中执行查询操作。通过 JDBC,web程序可以轻松地与关系型数据库进行交互,使应用程序的开发更加快速和高效。