今天寫Servlet的代碼需要連接到數據庫,但是由於最近沒有寫過數據庫的代碼,頻繁出錯,所以有必要記錄下來,下次遇到這種情況可以及時修正
首先連接數據庫需要的步驟
1.通過反射加載Driver類
1 String className = "com.mysql.jdbc.Driver";
2 Class.forName(className);
2.創建連接通道
1 String url = "jdbc:mysql://localhost/dbjdbc"; 2 String dbuser ="root"; 3 String dbpassword = "123456"; 4 5 Connection con = null; 6 con = DriverManager.getConnection(url, dbuser, dbpassword);
3.創建Statement
1 Statement statement = null;
2 statement = con.createStatement();
4.執行數據庫操作
ResultSet rs= null; rs = statement.executeQuery("select password from db_users where username='"+username+"'"); //說明用戶存在 if(rs.next()) { String passw=rs.getString(1); if(passw.equals(password)) { //得到Session HttpSession hs = req.getSession(true); //修改Session存在時間 hs.setMaxInactiveInterval(30); //Session添加屬性pass hs.setAttribute("pass", "ok"); res.sendRedirect("welcome?uname="+username+"&upassw="+password+"&sx="+sex); } else { //說明密碼錯誤 res.sendRedirect("login?info=error1"); } } else { //說明用戶名不存在 res.sendRedirect("login?info=error1"); }
另外就是在寫Servlet中發現的問題
java.lang.ClassNotFoundException: com.mysql.jdbc.Driver(Servlet鏈接mysql數據庫失敗解決方法)
在寫代碼的過程中都有向Ecplipse中導入了連接MySQL的jar包,但總是報數據庫連接失敗,找不到Driver類,其實是因為服務器去找Driver類的時候找不到,可以在tomcat安裝目錄下的lib文件夾里添加jar包一勞永逸,也可以在本工程目錄下的WEB-INF/lib中添加jar包,但后者在部署時也需要將lib中的jar包記得copy到相應的lib文件夾中
另外在連接數據庫中導包java.sql.*;