jdbc数据池配置文件读取
1.添加配置文件 jdbc.properties
jdbc.userName = root
jdbc.password = sepc1234
jdbc.driverClassName = com.mysql.jdbc.Driver
jdbc.url = jdbc:mysql://192.168.3.182:13306/cwjh
2.建立连接
public static Connection JdbcConnect() throws Exception {
//从根目录读取文件 Properties pro=new Properties(); InputStream in = ApiServiceTest.class.getResourceAsStream("/main/resources/config/JDBC.properties"); Connection conn = null; try { //1.加载properties配置文件 pro.load(in); String user = pro.getProperty("jdbc.userName"); String password = pro.getProperty("jdbc.password"); String jdbcurl = pro.getProperty("jdbc.url"); //2。建立数据池连接 conn = DriverManager.getConnection(jdbcurl, user, password); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); }finally { in.close(); return conn; } } public static void closeAll(Connection conn, PreparedStatement st) throws Exception { try { //关闭连接 if (st != null) { st.close(); } if (conn != null) { conn.close(); } } catch (Exception e) { // TODO: handle exception e.printStackTrace(); } }
3.使用
try { //建立连接 Connection conn = httpClientUnit.JdbcConnect(); PreparedStatement st = null; String SQL = "insert into "+ tableName+"(username,password) values(?,?)"; st = conn.prepareStatement(SQL); for (int j = 0; j < data.size(); j++) { Map<String, Object> map2 = new HashMap<>(); st.setObject(1, map2.get("")); st.setObject(2, map2.get("")); st.setObject(3, map2.get("")); st.setObject(4, map2.get("")); st.setObject(5, map2.get("")); st.setObject(6, map2.get("")); st.setObject(7, map2.get("")); st.setObject(8, map2.get("")); int rs1 = st.executeUpdate(); if (rs1 != 0) { System.out.println("插入成功!"); } } httpClientUnit.closeAll(conn,st); } catch (Exception e) { // TODO: handle exception e.printStackTrace(); }