servlet mysql 入門



簡單的小例子,查詢下,打印出第一個字段的內容。不能再簡單了 千里之行,始於helloword

public void doGet(HttpServletRequest req, HttpServletResponse res){
String url = "jdbc:mysql://localhost:3306/mytest"; 

 Connection con= null;
Statement stat= null;
ResultSet rs = null;
res.setContentType("text/html;charset=utf-8");  try{
      try{
// Class.forName("org.gjt.mm.mysql.Driver").newInstance();
Class.forName("com.mysql.jdbc.Driver");
      }
catch (Exception ex){
      return;
}


      try{                  
       con = DriverManager.getConnection(url,"root","root");
       stat = con.createStatement();
       String sqlString= "select * from a";
       rs = stat.executeQuery(sqlString);
       while (rs.next()){                             
        System.out.println(rs.getString(0));
        }
      rs.close();
      stat.close();
      con.close();
}
      catch (SQLException ex){

       if(rs!=null)   rs.close();
if(stat!=null) stat.close();
if(con!=null) con.close();

       while (ex !=null){
         ex.printStackTrace(pw);
         ex = ex.getNextException();
}
}
}
catch (Exception ex){
ex.printStackTrace();
}
}


驗證好後,就要開始大規模操作了啊,不要怕啊。我來了

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章