Servlet学习之四连接数据库

来源:互联网 发布:龙之谷g友戒指淘宝 编辑:程序博客网 时间:2024/05/18 00:27

要连接数据库:

1、加载驱动

2、获取连接字符串

3、创建Statement

4、执行查询语句

如下列所示:

Connection ct=null;Statement sm=null;ResultSet rs=null;Class.forName("com.microsoft.jdbc.sqlserver.SQLServerDriver");ct=DriverManager.getConnection("jdbc:microsoft:sqlserver://127.0.0.1:1433;databaseName=spdb","sa","123456");sm=ct.createStatement();rs=sm.executeQuery("select top 1 passwd from users where username='"+u+"' and passwd='"+p+"'");if(rs.next()){   //说明用户名存在   String dbPasswd=rs.getString(1);   if(dbPasswd.equals(p))   {     //真的合法     //合法     //跳转到wel     //将验证成功的信息写入session     //1、得到session     HttpSession hs=req.getSession(true);     //修改session的存在时间     hs.setMaxInactiveInterval(20);     hs.setAttribute("pass","ok");     res.sendRedirect("wel?uname="+u+"&upasswd="+p);    }      }else{     //说明用户名不存在     res.sendRedirect("login"); }try{    if(rs!=null){    rs.close();     }    if(sm!=null){    sm.close();    }     if(ct!=null){     ct.close();    }         }catch(Exception ex){     ex.printStackTrace();}}


0 0