java JDBC (五) properties配置文件

时间:2022-09-28 19:32:32

1、在src目录下创建文件 database.properties

driver = com.mysql.jdbc.Driver
url = jdbc:mysql://192.168.0.207:3306/mydb
user = root
pwd = XXXXXXXXXXXX

2、创建读取配置文件信息的类DBProperties.java

package cn.sasa.demo4;

import java.io.IOException;
import java.io.InputStream;
import java.util.Properties; public class DBProperties {
public static String driver = "";
public static String url = "";
public static String user = "";
public static String pwd = ""; static {
// 类的加载器
try {
InputStream input = DBProperties.class.getClassLoader().getResourceAsStream("database.properties");
Properties properties = new Properties();
properties.load(input);
driver = properties.getProperty("driver");
url = properties.getProperty("url");
user = properties.getProperty("user");
pwd = properties.getProperty("pwd");
}catch(IOException ex) { } }
}

3、JDBC的工具类

package cn.sasa.demo4;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement; /***
* JDBC 工具类
* @author THTF
*
*/
public class JDBCUtil { private JDBCUtil() {} private static Connection conn; static {
try {
Class.forName(DBProperties.driver);
String url = DBProperties.url;
String user = DBProperties.user;
String pwd = DBProperties.pwd;
conn = DriverManager.getConnection(url, user, pwd);
}catch(Exception ex){
throw new RuntimeException(ex + "数据库连接失败");
}
} /**
* 获得连接
*/
public static Connection getConn() {
return conn;
} /**
* 关闭资源
*/
public static void close(Connection con, Statement state, ResultSet rs) {
if(con != null) {
try {
con.close();
}catch(SQLException ex){ }
}
if(state != null) {
try {
state.close();
}catch(SQLException ex){ }
}
if(rs != null) {
try {
rs.close();
}catch(SQLException ex){ }
}
} public static void close(Connection con, Statement state) {
if(con != null) {
try {
con.close();
}catch(SQLException ex){ }
}
if(state != null) {
try {
state.close();
}catch(SQLException ex){ }
}
}
}

4、测试类

package cn.sasa.demo4;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList; public class TestJDBCUtil {
public static void main(String[] args) throws SQLException {
Connection conn = JDBCUtil.getConn(); String sql = "SELECT * FROM product;";
PreparedStatement pstate = conn.prepareStatement(sql);
ResultSet rs = pstate.executeQuery(); ArrayList<Product> plist = new ArrayList<Product>();
while(rs.next()) {
Product p = new Product(rs.getInt("pid"),
rs.getString("pname"),
rs.getDouble("price"),
rs.getString("ptype"),
rs.getString("create_tm")
);
plist.add(p);
} JDBCUtil.close(conn, pstate, rs); for(var p : plist) {
System.out.println(p.getPname() +"\t"+ p.getPrice());
}
}
}