静态代码块加载properties配置文件,注册驱动
静态方法创建连接
静态方法关闭,一个方法关connection,statement,另一个方法多关一个resultSet
package com.aistart.tech.until;
import java.io.IOException;
import java.sql.*;
import java.util.Properties;
public class JDBCUtil {
public static final Properties info = new Properties();
static {
try {
info.load(JDBCUtil.class.getClassLoader().getResourceAsStream("com/aistart/tech/config/jdbc.properties"));
Class.forName(info.getProperty("driver"));
} catch (ClassNotFoundException e) {
throw new RuntimeException(e);
} catch (IOException e) {
throw new RuntimeException(e);
}
}
public static Connection getConnection() throws SQLException {
//获取配置中的url
String url = info.getProperty("url");
//获取用户和密码
String user = info.getProperty("user");
String password = info.getProperty("password");
Connection connection = null;
if (connection==null){
connection = DriverManager.getConnection(url,user,password);
}
return connection;
}
public static void closeAll(Connection connection, Statement statement){
if (statement != null) {
try {
statement.close();
} catch (SQLException e) {
throw new RuntimeException(e);
}
}
if (connection != null) {
try {
connection.close();
} catch (SQLException e) {
throw new RuntimeException(e);
}
}
}
public static void closeAll(Connection connection, Statement statement, ResultSet resultSet){
if (resultSet != null) {
try {
resultSet.close();
} catch (SQLException e) {
throw new RuntimeException(e);
}
}
closeAll(connection,statement);
}
}
创建Map,键代表字段别名
把id传入占位符中执行sql
获取元数据的列数,根据列数循环获取每列的别名及相应的值,put到Map中
//根据id获取一行内容
public Map<String, Object> getEmpInfoById(int id) {
Map<String, Object> map = new HashMap<>();
Connection connection =null;
PreparedStatement preparedStatement = null;
ResultSet resultSet = null;
try {
connection = JDBCUtil.getConnection();
preparedStatement = connection.prepareStatement("select e.last_name as emp_name,job_title from employees e left join jobs j on e.job_id = j.job_id\n" +
"where employee_id =? ");
preparedStatement.setInt(1,id);
resultSet= preparedStatement.executeQuery();
//获取结果的列信息,元数据
ResultSetMetaData metaData = resultSet.getMetaData();
//获取总共有几列
int columnCount = metaData.getColumnCount();
if (resultSet.next()){
for (int i = 1; i <= columnCount ; i++) {
//是对应数据库表中原本的列名
String columnName = metaData.getColumnName(i);
//返回的table中名字(如果取别名,拿到就是别名)
String columnLabel = metaData.getColumnLabel(i);
map.put(columnLabel,resultSet.getString(columnLabel));
// map.put()
}
return map;
}
} catch (SQLException e) {
throw new RuntimeException(e);
}finally {
JDBCUtil.closeAll(connection,preparedStatement,resultSet);
}
return null;
}
@Test
public void empTest(){
Map<String, Object> empInfoById = iEmpDao.getEmpInfoById(100);
System.out.println(empInfoById.get("emp_name"));
System.out.println(empInfoById.values());
}