Make sure you have taken the following steps:
If using maven, make sure that you have the following dependency in your pom file (if using JDK7/8):
com.zaxxer
HikariCP
2.0.1
compile
If using another build tool, change the resource URL accordingly (or just download the jar file from the maven repository if there is no other option for you).
I believe you need the sqljdbc4.jar file in your pom file as well (I could be wrong about this requirement so I may update the post once I reconfirm)
Import the following in your class along with other references:
import com.zaxxer.hikari.HikariConfig;
import com.zaxxer.hikari.HikariDataSource;
Add the following final properties (or simply load them from config file):
private final String url = "jdbc:sqlserver://";
private final String serverName= "xxx.xxx.xxx.xxx";
private final int portNumber = 1433;
private final String databaseName= "ACTUALDBNAME";
private final String userName = "ACTUALUSERNAME";
private final String password = "ACTUALPASSWORD";
private final String selectMethod = "cursor";
You can retrieve the connection URL like this:
public String getConnectionUrl() {
return url+this.serverName+":"+this.portNumber+";databaseName="+this.databaseName+";user="+this.userName+";password="+this.password+";selectMethod="+this.selectMethod+";";
}
Then, the following should give you the DataSource you need in order to get a connection:
public DataSource getDataSource() {
final HikariDataSource ds = new HikariDataSource();
ds.setMaximumPoolSize(10);
ds.setDataSourceClassName("com.microsoft.sqlserver.jdbc.SQLServerDataSource");
// ds.addDataSourceProperty("serverName", this.serverName);
//ds.addDataSourceProperty("databaseName", this.databaseName);
ds.addDataSourceProperty("url", this.getConnectionUrl());
ds.addDataSourceProperty("user", this.userName);
ds.addDataSourceProperty("password", this.password);
ds.setInitializationFailFast(true);
ds.setPoolName("wmHikariCp");
return ds;
}
or
public DataSource getDataSource() {
HikariConfig config = new HikariConfig();
config.setMaximumPoolSize(10);
config.setDataSourceClassName("com.microsoft.sqlserver.jdbc.SQLServerDataSource");
config.addDataSourceProperty("serverName", this.serverName);
config.addDataSourceProperty("port", this.portNumber);
config.addDataSourceProperty("databaseName", this.databaseName);
config.addDataSourceProperty("user", this.userName);
config.addDataSourceProperty("password", this.password);
return new HikariDataSource(config); //pass in HikariConfig to HikariDataSource
}
The preferred route is to pass the HikariConfig to the HikariDataSource constructor. You can also load the config from a properties file.
Then get connection from the datasource:
Connection con = null;
con = ds.getConnection(); //where ds is the dataSource retrieved from step 5