此也是将数据库与java 的JDBC连接
//这是将db.properties数据流放入内存中 InputStream ins = Thread.currentThread().getContextClassLoader().getResourceAsStream("db.properties"); pro.load(ins); driver=pro.getProperty("driver"); url=pro.getProperty("url"); username=pro.getProperty("username"); password=pro.getProperty("password"); ins.close();
db.properties
#MySql #driver=com.mysql.jdbc.Driver #url=jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=utf-8 #username=root #password=root #oracle driver=oracle.jdbc.driver.OracleDriver url=jdbc:oracle:thin:@127.0.0.1:1521:orcl username=scott password=tiger
DBUtil.java
package com.edusk.util; import java.io.IOException; import java.io.InputStream; import java.sql.Connection; import java.sql.DriverManager; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.util.Properties; public class DBUtil { private static String driver = ""; private static String url = ""; private static String username = ""; private static String password = ""; private Connection conn = null; /* * 静态代码块 */ static{ Properties pro = new Properties(); try { //这是将db.properties数据流放入内存中 InputStream ins = Thread.currentThread().getContextClassLoader().getResourceAsStream("db.properties"); pro.load(ins); driver=pro.getProperty("driver"); url=pro.getProperty("url"); username=pro.getProperty("username"); password=pro.getProperty("password"); ins.close(); } catch (IOException e) { e.printStackTrace(); } } public Connection getConnection() { try { Class.forName(driver); conn = DriverManager.getConnection(url, username, password); } catch (ClassNotFoundException | SQLException e) { e.printStackTrace(); } return conn; } /** * 关闭链接 * @param con * @param ps * @param rs */ public static void close(Connection conn,PreparedStatement ps,ResultSet rs){ if(conn!=null){ try { conn.close(); } catch (SQLException e) { e.printStackTrace(); } } if(ps!=null){ try { ps.close(); } catch (SQLException e) { e.printStackTrace(); } } if(rs!=null){ try { rs.close(); } catch (SQLException e) { e.printStackTrace(); } } } }
测试文件
TestConnection.java
package com.edusk.test; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import com.edusk.util.DBUtil; public class TestConnection { public static void main(String[] args) { Connection conn = new DBUtil().getConnection(); try { PreparedStatement ps = conn.prepareStatement("select empno, ename from emp"); ResultSet rs = ps.executeQuery(); while(rs.next()) { System.out.println(rs.getInt(1)+" "+rs.getString(2)); } } catch (SQLException e) { e.printStackTrace(); } } }
时间: 2024-10-13 00:59:02