1 package dao; 2 3 import java.sql.Connection; 4 import java.sql.DriverManager; 5 import java.sql.PreparedStatement; 6 import java.sql.ResultSet; 7 import java.sql.SQLException; 8 import java.sql.Statement; 9 10 public class BaseDao { 11 private static String URL = "jdbc:sqlserver://localhost:1433;DatabaseName=StudentManageSys"; 12 private static String USER = "sa"; 13 private static String PWD = "sa"; 14 protected Connection conn = null; 15 protected PreparedStatement pstmt = null; 16 17 static { 18 try { 19 Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver"); 20 } catch (ClassNotFoundException e) { 21 e.printStackTrace(); 22 } 23 } 24 25 protected Connection getConnection() { 26 try { 27 return conn == null ? DriverManager.getConnection(URL, USER, PWD) : conn; 28 } catch (SQLException e) { 29 e.printStackTrace(); 30 return null; 31 } 32 } 33 34 protected void closeAll(Connection conn, Statement stmt, ResultSet rs) { 35 try { 36 if (conn != null) 37 conn.close(); 38 if (stmt != null) 39 stmt.close(); 40 if (rs != null) 41 rs.close(); 42 } catch (SQLException e) { 43 e.printStackTrace(); 44 } 45 } 46 47 protected Object execute(String sql, Object... objs) { 48 handle(sql, objs); 49 try { 50 boolean flag = pstmt.execute(); 51 return flag ? pstmt.getResultSet() : pstmt.getUpdateCount(); 52 } catch (SQLException e) { 53 e.printStackTrace(); 54 return null; 55 } 56 } 57 58 private void handle(String sql, Object[] objs) { 59 conn = getConnection(); 60 try { 61 pstmt = conn.prepareStatement(sql); 62 if (objs != null) { 63 for (int i = 0; i < objs.length; i++) { 64 pstmt.setObject(i + 1, objs[i]); 65 } 66 } 67 } catch (SQLException e) { 68 e.printStackTrace(); 69 } 70 } 71 }
上第二學期學Servlet的時候寫的簡單的工具類,畢業了之後又改進了一下,技術還處於菜鳥級別,也只能改成這樣了,祝我天天進步!