从properties文件中读取配置
properties内容
aaa.properties
DBDRIVER=com.mysql.jdbc.Driver
DBURL=jdbc:mysql://127.0.0.1:3306/demo?useSSL=false&serverTimezone=UTC&useUnicode=true&characterEncoding=UTF-8
DBUSER=123456
DBPASS=123456
java代码
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.InputStream;
import java.sql.*;
import java.util.*;
public class SqlUtil {
private static Logger logger = LoggerFactory.getLogger(SqlUtil.class);
//定义MySQL的数据库驱动程序
private static String DBDRIVER = "";
//定义MySQL数据库的连接地址
private static String DBURL = "";
//MySQL数据库的连接用户名
private static String DBUSER = "";
//MySQL数据库的连接密码
private static String DBPASS = "";
//定义数据库查询语句
private static final String querySql = "select id,name from table";
static {
try {
//从配置文件中读取字段
logger.info("load mybatisconfig.properties");
InputStream in = SqlUtil.class.getResourceAsStream("/mybatisconfig.properties");
//BufferedReader bf = new BufferedReader(new InputStreamReader(in));//这一句使用来读取中文用的
Properties prop = new Properties();
prop.load(in);//加载属性列表
DBDRIVER = prop.getProperty("DBDRIVER");
DBURL = prop.getProperty("DBURL");
DBUSER = prop.getProperty("DBUSER");
DBPASS = prop.getProperty("DBPASS");
in.close();
} catch (Exception e) {
logger.error("获取数据库配置失败: "+e);
}
}
/**
* @Description 从数据库查询数据
*/
public static List<Map<String, Object>> getData() {
Connection con = null;
Statement stmt = null;
ResultSet rs = null;
List<Map<String, Object>> returnList = new ArrayList<>();
try {
//加载驱动程序
Class.forName(DBDRIVER);
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
try {
//连接MySQL数据库时,要写上连接的用户名和密码
con = DriverManager.getConnection(DBURL, DBUSER, DBPASS);
//实例化Statement对象
stmt = con.createStatement();
//执行数据库查询操作
rs = stmt.executeQuery(querySql);
while (rs.next()) {
Map<String, Object> map = new HashMap<>();
map.put("id", rs.getString("id"));
map.put("name", rs.getString("name"));
returnList.add(map);
}
logger.info(Arrays.toString(returnList.toArray()));
} catch (SQLException e) {
logger.error("获取数据失败: "+e);
} finally {
//关闭数据库连接
try {
con.close();
} catch (SQLException e) {
logger.error("关闭数据库连接失败: "+e);
}
}
return returnList;
}
}