1、为了程序更好的解耦合,在MyJDBCUtils中加入Properties保存数据库的配置信息.
2、db.properties文件的内容如下
driver=com.mysql.jdbc.Driver url=jdbc:mysql://localhost:3306/testdatabase username=root password=12343、MyJDBCUtils的代码如下
package com.jdbc.utils; import java.sql.Connection; import java.sql.DriverManager; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; import java.util.Properties; public class MyJDBCUtils { // 为了程序的更好的解耦合,利用Properties文件保存连接Mysql的配置文件 private static Properties config = new Properties(); static { try { config.load(MyJDBCUtils.class.getClassLoader().getResourceAsStream( "db.properties")); Class.forName(config.getProperty("driver")); } catch (Exception e) { throw new ExceptionInInitializerError(e); } } public static Connection getConnection() { Connection conn = null; try { conn = DriverManager.getConnection(config.getProperty("url"), config.getProperty("username"), config.getProperty("password")); } catch (SQLException e) { throw new RuntimeException("获取连接Mysql数据库连接失败"); } return conn; } public static void release(Connection conn, Statement st, ResultSet rs) { if (rs != null) { try { rs.close(); } catch (Exception e) { throw new RuntimeException("ResultSet关闭异常"); } rs = null; } if (st != null) { try { st.close(); } catch (Exception e) { throw new RuntimeException("Statement关闭异常"); } st = null; } if (conn != null) { try { conn.close(); } catch (Exception e) { throw new RuntimeException("Connection关闭异常"); } conn = null; } } }
package com.jdbc.utils; import java.sql.Connection; import java.sql.ResultSet; import java.sql.Statement; import org.junit.Test; public class TestMyJDBCUtils { @Test public void testMyJDBCUtils() { Connection conn = null; Statement st = null; ResultSet rs = null; try { conn = MyJDBCUtils.getConnection(); st = conn.createStatement(); rs = st.executeQuery("select * from user "); while (rs.next()) { int id = rs.getInt(rs.findColumn("id")); String uname = rs.getString(rs.findColumn("uname")); int age = rs.getInt(rs.findColumn("age")); // 遍历输出 System.out.println("id " + id + " " + "uname " + uname + " " + "age " + age + " "); } } catch (Exception e) { throw new RuntimeException(e); } } }