Servlet连接oracle:

//1.仔细检查连接串。
//2.确认有没有这个表。
//3.如果出错了,先去后台看报错的信息。
//4.确认oracle已经启动了。
//5.把oracle的驱动D:\oracle\product\10.2.0\db_1\jdbc\lib\ojdbc14.jar拷贝到D:\Tomcat5.5.17\webapps\my\WEB-INF\lib。(因为运行时需要该jar包)

import Java.io.*;
import Java.sql.*;

public class ShowRs extends HttpServlet {

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

        Connection conn = null;
        Statement stmt = null;
        ResultSet rs = null;
        
        response.setContentType("text/html");
        response.setCharacterEncoding("gb2312");
        PrintWriter out = response.getWriter();
        
        out.println("<table border=1>");
        out.println("<tr><td>Content:</td></tr>");
        try {
            Class.forName("oracle.jdbc.driver.OracleDriver");
            conn = DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:orcl", "scott", "abc123");
            stmt = conn.createStatement();
            rs = stmt.executeQuery("select * from emp"); 
            while(rs.next()){
                out.println("<tr>");
                out.println("<td>" + rs.getString("ename") + "</td>");
                out.println("</tr>");
            }
            out.println("</table>");
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            try {
                if(rs != null) {
                    rs.close();
                    rs = null;
                }
                if(stmt != null) {
                    stmt.close();
                    stmt= null;
                }
                if(conn != null) {
                    conn.close();
                    conn = null;
                }
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }

}

 

posted on 2014-04-23 16:54  mosquito_real  阅读(889)  评论(0编辑  收藏  举报