日期:2014-05-19 浏览次数:20760 次
package jdbc; import java.io.IOException; import java.sql.*; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; public class JDBCTest extends HttpServlet { public void process(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException{ Connection conn=null;//连接对象 PreparedStatement pstmt=null;//预编译的语句对象 ResultSet rs=null;//查询结果集 String sql=null; try{ Class.forName("com.mysql.jdbc.Driver");//加载驱动 //建立连接 conn=DriverManager.getConnection("jdbc:mysql://localhost:3306/jdbctest","root","root"); //创建语句对象 sql="select*from myuser where user_id=?and user_pass=?"; pstmt=conn.prepareStatement(sql); pstmt.setString(1, "zhangsan"); pstmt.setString(2, "123"); rs=pstmt.executeQuery();//执行SQL语句 //处理结果 while(rs!=null&&rs.next()){ System.out.println("user_no"+rs.getString(1)); System.out.println("user_id="+rs.getString(2)); System.out.println("user_email="+rs.getString(5)); } }catch(Exception e){ System.out.println("数据库异常"); e.printStackTrace(); }finally{//按打开对象的逆序关闭对象 try{ if(rs!=null) rs.close(); if(pstmt!=null) pstmt.close(); if(conn!=null) conn.close(); }catch(Exception e){ } } } public JDBCTest() { super(); } public void destroy() { super.destroy(); // Just puts "destroy" string in log } public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { process(request,response); } public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { process(request,response); } public void init() throws ServletException { } }