JDBC 封装工具类

来源:互联网 发布:公务员网络培训系统 编辑:程序博客网 时间:2024/06/05 15:20

1.配置文件 jdbc.properties

driverClass=com.mysql.jdbc.Driverurl=jdbc:mysql:///mydb?useServerPrepStmts=true&cachePrepStmts=true&rewriteBatchedStatements=trueusername=rootpassword=root

2.封装工具类 jdbcUtils   

import java.sql.Connection;import java.sql.DriverManager;import java.sql.PreparedStatement;import java.sql.ResultSet;import java.sql.SQLException;import java.sql.Statement;import java.util.ResourceBundle;public class JdbcUtils2 {private static final String DRIVERCLASS;private static final String URL;private static final String USERNAME;private static final String PASSWORD;static {DRIVERCLASS = ResourceBundle.getBundle("jdbc").getString("driverClass");URL = ResourceBundle.getBundle("jdbc").getString("url");USERNAME = ResourceBundle.getBundle("jdbc").getString("username");PASSWORD = ResourceBundle.getBundle("jdbc").getString("password");}// 将加载驱动操作,放置在静态代码块中.这样就保证了只加载一次.static {try {Class.forName(DRIVERCLASS);} catch (ClassNotFoundException e) {// TODO Auto-generated catch blocke.printStackTrace();}}//获取连接public static Connection getConnection() throws SQLException {Connection con = DriverManager.getConnection(URL, USERNAME, PASSWORD);return con;}//关闭操作public static void closeConnection(Connection con) {try {if (con != null)con.close();} catch (SQLException e) {e.printStackTrace();}}public static void closeStatement(Statement st) {try {if (st != null)st.close();} catch (SQLException e) {e.printStackTrace();}}public static void closeResultSet(ResultSet rs) {if (rs != null) {try {rs.close();} catch (SQLException e) {// TODO Auto-generated catch blocke.printStackTrace();}}}public static void closePreparedStatement(PreparedStatement pst) {try {if (pst != null)pst.close();} catch (SQLException e) {e.printStackTrace();}}}

原创粉丝点击