例如,我有一个表单,用于放置数据库连接的用户,密码,端口等,并在将连接提交到数据库时进行保存。通常,这是在应用程序运行之前在application.properties中完成的,但是我可以在运行时将其添加到应用程序中吗?如果可以,我该怎么办?
答案 0 :(得分:1)
在我的一个项目中,我遇到了类似的情况,使用spring-jdbc很难编写代码和维护。您可以使用普通的jdbc通过连接参数来获取指定的连接对象。
package com;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.sql.Timestamp;
import org.apache.commons.lang3.exception.ExceptionUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.util.Assert;
@Component
public class DB2Connection {
private static final Logger logger = LoggerFactory.getLogger(DB2Connection.class);
private static String DRIVER_NAME;
private static String VALID_QUERY;
@Value("${db.valid-query}")
public void setValidQuery(String query){
VALID_QUERY = query;
}
@Value("${db.driverName}")
public void setDriverName(String driverName){
DRIVER_NAME = driverName;
}
/**
* Getting the Database connection
* @param url url of the database
* @param userName username of the db
* @param password password of the db
* @return Connection returns DB Connection object
* */
public static Connection getConnection(final String url, final String userName, final String password){
logger.info("Getting DB Connection...");
Assert.notNull(url, "Database URL can't be null");
Assert.notNull(userName, "Database username can't be null");
Assert.notNull(password, "Database password can't be null");
Connection con = null;
try{
Class.forName(DRIVER_NAME);
con = DriverManager.getConnection(url,userName,password);
// testing for the valid connection
if(testConnection(con)){
logger.info("Valid DB Connection # Connection Tested...");
}else{
logger.info("In-Valid DB Connection...");
}
}catch(ClassNotFoundException cla){
logger.error("Class Not found exception..."+ExceptionUtils.getStackTrace(cla));
}catch(SQLException sqe){
logger.error("SQL Exception..."+ExceptionUtils.getStackTrace(sqe));
}catch(Exception exe){
logger.error("Exception occured while making DB Connection..."+ExceptionUtils.getStackTrace(exe));
}
return con;
}
/**
* Closing the java.sql.Connection class object
*
* @param con Connection object which need to be closed
*
* */
public static void close(Connection con){
logger.info("Closing the connection object...");
try {
if(con != null ){
con.close();
}
} catch (SQLException e) {
logger.error("Exception occured while closing DBConnection..."+ExceptionUtils.getStackTrace(e));
}
}
/**
* This method will test connection if proper or not
* @param con Connection object which need to be checked
* @return flag true if connection is fine, false in case of connection is wrong
* */
public static synchronized boolean testConnection(Connection con){
boolean flag = false;
logger.info("Testing the connection before providing to another process...");
ResultSet rs = null;
Statement stmt = null;
try{
stmt= con.createStatement();
// running the query for validation of the database
rs = stmt.executeQuery(VALID_QUERY);
while(rs.next()){
// if we get Timestamp as return type - valid query is successfully run in the database
Timestamp t = rs.getTimestamp(1);
if( t != null){
flag =true;
}
}
}catch(SQLException e){
logger.error("SQL Exception error..."+ExceptionUtils.getStackTrace(e));
}finally{
if(rs != null){
try {
rs.close();
} catch (SQLException e) {
logger.error("Error in closing Result Set"+ExceptionUtils.getStackTrace(e));
}
}if( stmt != null){
try {
stmt.close();
} catch (SQLException e) {
logger.error("Error in closing Statement"+ExceptionUtils.getStackTrace(e));
}
}
}
return flag;
}
}
在application.properties文件中定义db.valid-query和db.driverName的值。 调用getConnection()来获取连接对象。
您还可以创建自己的自定义执行器,该执行器可以向您显示应用程序中当前正在运行的所有当前连接对象。维护当前对象DB Connection对象所需的额外代码。
答案 1 :(得分:1)
一种解决方案是使用您提到的所有必需的连接属性(加上一个DatabaseConnection
属性)创建一个active: boolean
实体。使用Spring Data为该实体创建存储库并创建上层组件。为您的客户提供控制器,以对该实体进行CRUD。
DatabaseConnectionService可以提供与其他组件的活动JDBC连接以进行查询/更新。