一、编译环境
- JDK:1.8
- IDEA:2023.1.2
二、maven依赖
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.28</version>
</dependency>
<!-- https://mvnrepository.com/artifact/com.oracle.database.jdbc/ojdbc8 -->
<dependency>
<groupId>com.oracle.database.jdbc</groupId>
<artifactId>ojdbc8</artifactId>
<version>23.2.0.0</version>
</dependency>
<dependency>
<groupId>com.oracle.database.nls</groupId>
<artifactId>orai18n</artifactId>
<version>23.2.0.0</version>
</dependency>
三、JDBCUtils
package main.com.xl.utils;
import main.com.xl.eunm.JDBCEunm;
import java.sql.*;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class JDBCUtils {
/*
*
* @author xxxxx
* @date 2024/8/2/002 17:12
* @return java.sql.Connection
*/
public static void queryExample(JDBCEunm jdbcEunm, String sql) {
try {
Class.forName(jdbcEunm.getJDBC_DRIVER());
Connection connection = DriverManager.getConnection(jdbcEunm.getDB_URL(),jdbcEunm.getUSER(),jdbcEunm.getPASS());
PreparedStatement stmt = connection.prepareStatement(sql); // 创建对象并预编译
ResultSet resultSet = stmt.executeQuery();
System.out.println(convertList(resultSet));
resultSet.close();
stmt.close();
connection.close();
}catch (Exception e){
e.printStackTrace();
}
}
private static List<Map> convertList(ResultSet rs) throws SQLException{
List<Map> list = new ArrayList<>();
ResultSetMetaData md = rs.getMetaData();//获取键名
int columnCount = md.getColumnCount();//获取列的数量
while (rs.next()) {
Map<String,Object> rowData = new HashMap<>();//声明Map
for (int i = 1; i <= columnCount; i++) {
rowData.put(md.getColumnName(i), rs.getObject(i));//获取键名及值
}
list.add(rowData);
}
return list;
}
public static void main(String[] args) {
String mSQL = "*****************";
String oSQL = "*****************";
queryExample(JDBCEunm.ORACLE,oSQL);
queryExample(JDBCEunm.MYSQL,mSQL);
}
}
四、JDBCEunm
package main.com.xl.eunm;
public enum JDBCEunm {
MYSQL("com.mysql.cj.jdbc.Driver",
"jdbc:mysql://ip:端口号/数据库?useSSL=false&serverTimezone=UTC",
"root",
"root"),
ORACLE("oracle.jdbc.driver.OracleDriver",
"jdbc:oracle:thin:@ip:端口号:orcl",
"system",
"root");
private String JDBC_DRIVER;
private String DB_URL;
private String USER;
private String PASS;
JDBCEunm(String JDBC_DRIVER, String DB_URL, String USER, String PASS){
this.JDBC_DRIVER = JDBC_DRIVER;
this.DB_URL = DB_URL;
this.USER = USER;
this.PASS = PASS;
}
public String getJDBC_DRIVER() {
return JDBC_DRIVER;
}
public String getDB_URL() {
return DB_URL;
}
public String getUSER() {
return USER;
}
public String getPASS() {
return PASS;
}
@Override
public String toString() {
return "JdbcEunm{" +
"JDBC_DRIVER='" + JDBC_DRIVER + '\'' +
", DB_URL='" + DB_URL + '\'' +
", USER='" + USER + '\'' +
", PASS='" + PASS + '\'' +
'}';
}
}
标签:JDBC,String,URL,数据库,DRIVER,切换,PASS,public
From: https://www.cnblogs.com/Robin-Lin/p/18339356