English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

Acceso a base de datos Servlet

Este tutorial asume que ya conoce el funcionamiento de las aplicaciones JDBC.

Nota:

Direcciones de descarga de paquetes jar de varias versiones de mysql:https://downloads.mysql.com/archives/c-j/

En el proyecto java, solo necesita agregar mysql-connector-java-5.1.39-bin.jar puede ejecutar proyectos java.

Pero en el proyecto web de Eclipse, al ejecutar Class.forName("com.mysql.jdbc.Driver");, no buscará el controlador. Por lo tanto, en este ejemplo, necesitamos agregar mysql-connector-java-5.1.39-bin.jar copiado al directorio lib de tomcat.

Desde los conceptos básicos, creemos una tabla simple y creamos algunas entradas en la tabla.

Crear datos de prueba

A continuación, creamos w3Base de datos codebox, y crea la tabla websites, la estructura de la tabla es la siguiente:

CREATE TABLE `websites` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `name` char(20) NOT NULL DEFAULT '' COMMENT 'Nombre del sitio',
  `url` varchar(255) NOT NULL DEFAULT '',
  `alexa` int(11) NOT NULL DEFAULT '0' COMMENT 'Ranking Alexa',
  `country` char(10) NOT NULL DEFAULT '' COMMENT 'País',
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=10 DEFAULT CHARSET=utf8;

Insertar algunos datos:

INSERT INTO `websites` VALUES ('1', 'Google', 'https://www.google.cm/', ''1', 'USA'), ('2', '淘宝', 'https://www.taobao.com/', ''13', 'CN'), ('3', 'Sitio web básico', 'http://es.oldtoolbag.com5892', ''4', '微博', 'http://weibo.com/', ''20', 'CN'), ('5', 'Facebook', 'https://www.facebook.com/', ''3', 'USA');

La tabla de datos se muestra a continuación:


acceder a la base de datos

El siguiente ejemplo muestra cómo usar Servlet para acceder a w3codebox base de datos.

package com.w;3codebox.test;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.*;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
 * Clase de implementación de Servlet DatabaseAccess
 */
@WebServlet("/DatabaseAccess")
public class DatabaseAccess extends HttpServlet {
    private static final long serialVersionUID = 1L;
    // Nombre del driver JDBC y URL de la base de datos
    static final String JDBC_DRIVER = "com.mysql.jdbc.Driver";  
    static final String DB_URL = "jdbc:mysql://localhost:3306/w3codebox";
    
    // El nombre de usuario y la contraseña de la base de datos, deben ajustarse según su configuración
    static final String USER = "root";
    static final String PASS = "123456"; 
    /**
     * @see HttpServlet#HttpServlet()
     */
    public DatabaseAccess() {
        super();
        // TODO Auto-constructor de muestra generado
    }
    /**
     * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
     */
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        Connection conn = null;
        Statement stmt = null;
        // Establecer el tipo de contenido de la respuesta
        response.setContentType("text/html"/html;charset=UTF-8-8");
        PrintWriter out = response.getWriter();
        String title = "Servlet ejemplo de base de datos", - 教程(básico(oldtoolbag.com)";
        String docType = "<!DOCTYPE html>\n";
        out.println(docType) +
        "<html>\n" +
        "<head><title>" + title + "</title></head>\n" +
        "<body bgcolor="#f0f0f0">\n" +
        "<h1 align="center">" + title + "</h1>\n");
        try{
            // 注册 JDBC 驱动器
            Class.forName("com.mysql.jdbc.Driver");
            
            // 打开一个连接
            conn = DriverManager.getConnection(DB_URL,USER,PASS);
            // 执行 SQL 查询
            stmt = conn.createStatement();
            String sql;
            sql = "SELECT id, name, url FROM websites";
            ResultSet rs = stmt.executeQuery(sql);
            // 展开结果集数据库
            while(rs.next()){
                // 通过字段检索
                int id = rs.getInt("id");
                String name = rs.getString("name");
                String url = rs.getString("url");
    
                // 输出数据
                out.println("ID: ") + id);
                out.println(", 站点名称: " + name);
                out.println(", 站点 URL: " + url);
                out.println("<br />");
            }
            out.println("</body></html>");
            // 完成后关闭
            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();
            }
        }
       
    }
    /**
     * @ver también HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
     */
    protegido void doPost(HttpServletRequest request, HttpServletResponse response) lanza ServletException, IOException {
        // TODO Auto-generado método de plantilla
        doGet(request, response);
    }
}

Ahora, compilamos el siguiente Servlet y creamos la siguiente entrada en el archivo web.xml:

....
    <servlet>
        <servlet-nombre>DatabaseAccess</servlet-nombre>
        <servlet-clase>com.w3codebox.test.DatabaseAccess</servlet-clase>
    </servlet>
    <servlet-mapeo>
        <servlet-nombre>DatabaseAccess</servlet-nombre>
        <url-patrón>/TomcatTest/DatabaseAccess</url-patrón>
    </servlet-mapeo>
....

Ahora llamamos a este Servlet, ingrese el enlace: http://localhost:8080/TomcatTest/DatabaseAccess, se mostrará el siguiente resultado de respuesta: