Skip to content

Instantly share code, notes, and snippets.

@hseritt
Created June 27, 2016 01:54
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save hseritt/2c7d1eee0617868a128790499f6d75d5 to your computer and use it in GitHub Desktop.
Save hseritt/2c7d1eee0617868a128790499f6d75d5 to your computer and use it in GitHub Desktop.
Creating a database connection and using properties files
import java.io.IOException;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Properties;
import org.apache.log4j.Logger;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;
@Component
@ConfigurationProperties("spring.datasource")
public class DbConnector {
private static Logger logger = Logger.getLogger(DbConnector.class);
public Connection getConnection() throws SQLException, ClassNotFoundException, IOException {
Properties dbProps = new Properties();
InputStream in = ClassLoader.getSystemResourceAsStream("application.properties");
dbProps.load(in);
String driverClassName = dbProps.getProperty("spring.datasource.driver-class-name");
String url = dbProps.getProperty("spring.datasource.url");
String username = dbProps.getProperty("spring.datasource.username");
String password = dbProps.getProperty("spring.datasource.password");
logger.debug("Connecting with db type: " + driverClassName);
Class.forName(driverClassName);
logger.debug("Using: ");
logger.debug(" URL: " + url);
logger.debug(" DbUser: " + username);
logger.debug(" DbPasswd: " + password);
Connection connection = DriverManager.getConnection(url, username, password);
return connection;
}
public void close() throws IOException {
try {
getConnection().close();
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
}
}
public ResultSet query(String sql) throws ClassNotFoundException, SQLException, IOException {
Statement stmt = getConnection().createStatement();
ResultSet results = stmt.executeQuery(sql);
return results;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment