Created
June 27, 2016 01:54
-
-
Save hseritt/2c7d1eee0617868a128790499f6d75d5 to your computer and use it in GitHub Desktop.
Creating a database connection and using properties files
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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