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 || conn.isClosed()) ? 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 (rs != null)
37 rs.close();
38 if (stmt != null)
39 stmt.close();
40 if (conn != null)
41 conn.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 if (flag) {
52 return pstmt.getResultSet(); // 查询不必先释放资源
53 } else {
54 closeAll(conn, pstmt, null);
55 return pstmt.getUpdateCount();
56 }
57 } catch (SQLException e) {
58 e.printStackTrace();
59 return null;
60 }
61 }
62
63 private void handle(String sql, Object[] objs) {
64 conn = getConnection();
65 try {
66 pstmt = conn.prepareStatement(sql);
67 if (objs != null) {
68 for (int i = 0; i < objs.length; i++) {
69 pstmt.setObject(i + 1, objs[i]);
70 }
71 }
72 } catch (SQLException e) {
73 e.printStackTrace();
74 }
75 }
76 }