Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- package main;
- import java.sql.Connection;
- import java.sql.PreparedStatement;
- import java.sql.ResultSet;
- import java.sql.SQLException;
- import com.zaxxer.hikari.HikariConfig;
- import com.zaxxer.hikari.HikariDataSource;
- public class DataSource {
- private static HikariConfig config = new HikariConfig();
- private static HikariDataSource ds;
- static {
- config.setJdbcUrl("jdbc:mysql://localhost:3306/sampletable");
- config.setUsername("root");
- config.setPassword("00001");
- config.addDataSourceProperty("characterEncoding", "utf8");
- config.addDataSourceProperty("useUnicode", true);
- config.setMaximumPoolSize(10);
- config.setConnectionTimeout(5000);
- ds = new HikariDataSource( config );
- }
- public static Connection getConnection() throws SQLException {
- return ds.getConnection();
- }
- public static void main (String[] args) {
- getName("1");
- }
- public static String getName(String id) {
- Connection connection = null;
- PreparedStatement preparedStatement = null;
- ResultSet resultSet = null;
- try {
- //Get a connection from the connection pool
- connection = getConnection();
- //SQL Query
- String query = "SELECT * FROM TABLE1 WHERE ID = ?";
- //Prepare the statement
- preparedStatement = connection.prepareStatement(query);
- //Sets the cache size to 0
- preparedStatement.setFetchSize(0);
- //Basically defines the question marks in the query
- preparedStatement.setObject(1, id);
- //Gets the result
- resultSet = preparedStatement.getResultSet();
- //Loops through all the rows returned from the execution, if the ID is completely unique you will only have row (Unless you fucked up).
- while(resultSet.next()) {
- //In this case it should only have one value (you shouldn't even loop in this case)
- return resultSet.getString(1);
- }
- }catch(SQLException e) {
- e.printStackTrace();
- }finally{
- try {
- if(connection != null) connection.close();
- if(preparedStatement != null) preparedStatement.close();
- if(resultSet != null) resultSet.close();
- }catch(SQLException e) {
- e.printStackTrace();
- }
- }
- return null;
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement