servlet连接mysql

来源:互联网 发布:黄海 知乎 编辑:程序博客网 时间:2024/05/03 02:02
 

 // 定义MySQL的数据库驱动程序
   String DBDRIVER = "org.gjt.mm.mysql.Driver" ;
  // 定义MySQL数据库的连接地址
   String DBURL = "jdbc:mysql://localhost:3306/test" ;
  // MySQL数据库的连接用户名
   String DBUSER = "root" ;
  // MySQL数据库的连接密码
   String DBPASS = "" ;
  
   Connection conn =null;
   Statement st = null;
   ResultSet rs  = null;
   
 
   try{
    Class.forName(DBDRIVER) ; // 加载驱动程序
    System.out.println("连接成功") ; // 如果此时可以打印表示连接正常
   }catch(ClassNotFoundException e){
    e.printStackTrace() ;
   }


   try{

 // 连接数据库

    conn = DriverManager.getConnection(DBURL,DBUSER,DBPASS) ;

//创建一个 Statement 对象来将 SQL 语句发送到数据库。

    st = conn.createStatement();
    rs = st.executeQuery("select passwd from user where name  ='"+u+"' limit 1");


    if(rs.next()){
     String pd = rs.getString(1);

     if(pd.equals(p)){
      HttpSession hs = req.getSession(true);
      hs.setAttribute("name",u);
      hs.setMaxInactiveInterval(10);
      res.sendRedirect("welcome");
     }else{
      res.sendRedirect("login");
     }
     
    }  
   }catch(Exception e){
    e.printStackTrace();
   }

原创粉丝点击