servlet之JDBC操作

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.*;

/**
 * Created by solitude on 17-7-18.
 */
/*
关于jdbc的操作可以参考文章:http://blog.csdn.net/solitudesky/article/details/72827814

首先导入数据库驱动jar包
其次建立好要操作的数据库

 */
@WebServlet("/JDBCServlet")
public class JDBCServlet extends HttpServlet {
    private static final long serialVersionUID = 1L;
    // JDBC 驱动名及数据库 URL
    static final String DB_URL = "jdbc:mysql://localhost:3306/test";

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

    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doGet(request, response);
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        Connection conn = null;
        PreparedStatement ptst = null;

        response.setContentType("text/html;charset=UTF-8");
        PrintWriter out = response.getWriter();
        String title = "Servlet Mysql 测试";
        String docType = "\n";
        out.println(docType +
                "\n" +
                "" + title + "\n" +
                "\n" +
                "

" + title + "

\n"); try { Class.forName("com.mysql.jdbc.Driver"); conn = DriverManager.getConnection(DB_URL, USER, PASS); String sql = "SELECT id, name, url FROM websites"; ptst = conn.prepareStatement(sql); ResultSet rs = ptst.executeQuery(); // 展开结果集数据库 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("
"); } out.println(""); // 完成后关闭 rs.close(); ptst.close(); conn.close(); } catch (ClassNotFoundException e) { e.printStackTrace(); } catch (SQLException e) { e.printStackTrace(); } finally { // 最后是用于关闭资源的块 try{ if(ptst!=null) ptst.close(); }catch(SQLException se2){ } try{ if(conn!=null) conn.close(); }catch(SQLException se){ se.printStackTrace(); } } } }

你可能感兴趣的:(servlet/jsp)