昆明java培训
达内昆明广州春城路

18487146383

热门课程

JavaWeb基础:BaseDao

  • 时间:2016-09-28
  • 发布:昆明Java培训
  • 来源:达内新闻

今天昆明Java培训机构的老师给大家讲JavaWeb基础工具类——BaseDao

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 }

了解详情请登陆昆明达内Java培训官网(km.Java.tedu.cn)!

上一篇:java反射机制
下一篇:Java程序:基本类型的4个建议

上java培训有用吗?怎么衡量?【达内培训】

昆明java培训机构怎么选?昆明达内java培训怎么样?

学Java自学还是达内培训机构好?

0基础学java垃圾代码回收站【达内编程培训】

选择城市和中心
贵州省

广西省

海南省

台湾