postgresql sql语句不支持判断数据库是否存在,也不支持数据库连接url后面加createDatabaseIfNotExist=true
yml配置
spring:
servlet:
multipart:
max-request-size: 100MB
max-file-size: 100MB
datasource:
type: com.alibaba.druid.pool.DruidDataSource
driver-class-name: org.postgresql.Driver
url: jdbc:postgresql://12.0.0.1/test?useUnicode=true¤tSchema=public&zeroDateTimeBehavior=convertToNull&characterEncoding=UTF-8&allowMultiQueries=true&serverTimezone=Asia/Shanghai
username:
password:
package com.aaaa.test;
import com.sun.org.apache.xerces.internal.util.URI;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.annotation.Configuration;
import org.springframework.beans.factory.annotation.Value;
import javax.annotation.PostConstruct;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
@Configuration
public class DataSourceHelper {
private Logger log = LoggerFactory.getLogger(DataSourceHelper.class);
@Value("${spring.datasource.driver-class-name}")
private String driver;
@Value("${spring.datasource.url}")
private String url;
@Value("${spring.datasource.username}")
private String username;
@Value("${spring.datasource.password}")
private String password;
@PostConstruct
public void init() {
try {
Class.forName(driver);
URI uri = new URI(url.replace("jdbc:", ""));
String host = uri.getHost();
int port = uri.getPort();
String path = uri.getPath();
Connection connection = DriverManager.getConnection("jdbc:postgresql://" + host + ":" + port+"/postgres", username, password);
Statement statement = connection.createStatement();
ResultSet resultSet = statement.executeQuery("SELECT u.datname FROM pg_catalog.pg_database u where u.datname= '"+path.replace("/", "") +"';");
boolean flag=resultSet.next();
if(!flag){
statement.executeUpdate("CREATE DATABASE " + path.replace("/", "") + ";");
}
statement.close();
connection.close();
} catch (Exception e) {
log.error(e.getMessage());
}
}
}
文章提供了一个Java类,该类在Spring框架中使用DruidDataSource初始化时,会检查指定的数据库URL是否已存在,如果不存在则创建。代码通过加载驱动,解析URL获取主机、端口和路径信息,然后连接到postgres数据库进行查询,最后根据查询结果决定是否创建新的数据库。
1092





