获取数据库链接
/**
* @return
* @throws Exception
* @功能描述: 获取数据库连接
*/
public static Connection getMySqlConnection(String url, String userName, String userPassword) throws Exception {
Class.forName("com.mysql.cj.jdbc.Driver");
return DriverManager.getConnection(url, userName, userPassword);
}
执行select
/**
* 执行select
* @param url 链接路径
* @param username 用户名
* @param password 密码
* @param sql sql语句
* @return
* @throws Exception
*/
public static List<Map<String, Object>> executeGet(String url, String username, String password, String sql) throws Exception {
Statement statement = null;
ResultSet resultSet = null;
try {
Connection connection = getMySqlConnection(url,username,password);
statement = connection.createStatement();
resultSet = statement.executeQuery(sql);
ResultSetMetaData metaData = resultSet.getMetaData();
List<Map<String, Object>> resultList = new ArrayList<>();
while (resultSet.next()) {
Map<String, Object> dataMap = new HashMap<>();
for (int i = 1; i <= metaData.getColumnCount(); i++) {
dataMap.put(metaData.getColumnLabel(i), resultSet.getObject(i));
} resultList.add(dataMap);
}
return resultList;
} catch (Exception e) {
throw e;
} finally {
try {
if (resultSet != null) {
resultSet.close();
}
if (statement != null) {
statement.close();
}
} catch (SQLException e) {
}
}
}
调用示例
public static void main(String[] args) throws Exception {
String url = "jdbc:mysql://IP地址:端口号/数据库名称?useUnicode=true&characterEncoding=utf8&zeroDateTimeBehavior=convertToNull&useSSL=true&serverTimezone=GMT%2B8";
String username = "用户名";
String pwd = "链接密码";
String sql = "select data_code from gather_source;";
List<Map<String,Object>> result = ExecuteUtil.executeGet( url, username, pwd, sql);
//将结果转换成自己需要的格式
String str = StringUtil.getSrting(result);
System.out.println(str);
}