测试环境:win10
JDK版本:1.7.0_80
测试工具:NetBeans
package javaapplication2;
import java.sql.Connection;
import java.sql.DatabaseMetaData;
import java.sql.DriverManager;
public class JavaApplication2 {
/**
* @param args the command line arguments
* @throws java.lang.Exception
*/
public static void main(String[] args) throws Exception {
JavaApplication2 j2 = new JavaApplication2();
Class.forName("com.mysql.jdbc.Driver");
try (Connection connection = DriverManager.getConnection("jdbc:mysql://127.0.0.1:3306/test?useUnicode=true&characterEncoding=utf-8&autoReconnect=true", "root", "root");) {
DatabaseMetaData databaseMetaData1 = connection.getMetaData();
String url = databaseMetaData1.getURL();
System.out.println(j2.getDataBaseName(url));
}
}
/**
* 通过链接地址获取数据库名
*
* @param url 链接地址
* @return 数据库名
*/
public String getDataBaseName(String url) {
String urlAfterTreatment = url;
//判斷是否有問號
if (url.indexOf("?") != -1) {
urlAfterTreatment = urlAfterTreatment.substring(0, urlAfterTreatment.indexOf("?"));
}
//判斷是否有冒號
if (urlAfterTreatment.split(":").length > 1) {
String[] urlAfterTreatments = urlAfterTreatment.split(":");
urlAfterTreatment = urlAfterTreatments[urlAfterTreatments.length - 1];
}
//判斷是否有斜杆
if (urlAfterTreatment.split("/").length > 1) {
String[] urlAfterTreatments = urlAfterTreatment.split("/");
urlAfterTreatment = urlAfterTreatments[urlAfterTreatments.length - 1];
}
//判斷是否有等号(解决sqlserver的情况:jdbc:sqlserver://127.0.0.1:1433;databaseName=Mytest)
if (urlAfterTreatment.split("=").length > 1) {
String[] urlAfterTreatments = urlAfterTreatment.split("=");
urlAfterTreatment = urlAfterTreatments[urlAfterTreatments.length - 1];
}
return urlAfterTreatment;
}
}