mysql封装 javabean_JDBC Java 程序从 MySQL 数据库中读取数据,并封装到 Javabean 对象中...

1 packagecom.mk.util;2

3 importjava.io.IOException;4 importjava.sql.Connection;5 importjava.sql.DriverManager;6 importjava.sql.PreparedStatement;7 importjava.sql.ResultSet;8 importjava.sql.SQLException;9 importjava.sql.Statement;10 importjava.util.Properties;11

12 public classDBUtil {13 static Properties properties = null; //用于读取和处理资源文件中的信息

14 static { //类加载的时候被执行一次

15 properties = newProperties();16 try{17 properties.load(Thread.currentThread().getContextClassLoader().getResourceAsStream("db.properties"));18 } catch(IOException e) {19 e.printStackTrace();20 }21 }22

23 public staticConnection getConnection() {24 try{25 //加载 MySQL JDBC 驱动类

26 Class.forName(properties.getProperty("mysqlDriver"));27 //建立连接(连接对象内部其实包含了Socket对象,是一个远程的连接,比较耗时!这是Connection对象管理的一个要点!)28 //真正开发中,为了提高效率,都会使用连接池来管理连接对象!

29 String mysqlUrl = properties.getProperty("mysqlUrl");30 String mysqlUser = properties.getProperty("mysqlUser");31 String mysqlPassword = properties.getProperty("mysqlPassword");32 returnDriverManager.getConnection(mysqlUrl, mysqlUser, mysqlPassword);33 } catch(ClassNotFoundException e) {34 e.printStackTrace();35 return null;36 } catch(SQLException e) {37 e.printStackTrace();38 return null;39 }40 }41

42 public staticPreparedStatement getPreparedStatement(Connection connection, String sql) {43 try{44 //使用 PreparedStatement,防止 SQL 注入

45 returnconnection.prepareStatement(sql);46 } catch(SQLException e) {47 e.printStackTrace();48 return null;49 }50 }51

52 public static voidclose(Connection connection, Statement statement, ResultSet resultSet) {53 if (resultSet != null) {54 try{55 resultSet.close();56 } catch(SQLException e) {57 e.printStackTrace();58 }59 }60 if (statement != null) {61 try{62 statement.close();63 } catch(SQLException e) {64 e.printStackTrace();65 }66 }67 if (connection != null) {68 try{69 connection.close();70 } catch(SQLException e) {71 e.printStackTrace();72 }73 }74 }75

76 public static voidclose(Connection connection) {77 if (connection != null) {78 try{79 connection.close();80 } catch(SQLException e) {81 e.printStackTrace();82 }83 }84 }85

86 public static voidclose(Statement statement) {87 if (statement != null) {88 try{89 statement.close();90 } catch(SQLException e) {91 e.printStackTrace();92 }93 }94 }95

96 public static voidclose(ResultSet resultSet) {97 if (resultSet != null) {98 try{99 resultSet.close();100 } catch(SQLException e) {101 e.printStackTrace();102 }103 }104 }105 }

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值