【发布时间】:2014-08-17 23:34:23
【问题描述】:
我正在尝试找出将 hikaricp(JDBC 连接池)与 microsoft sql server 一起使用的最佳方法。据我所见,建议使用 DataSource 选项(就像我见过的大多数连接池一样)。但是,根据我看到的示例,我无法正确地与 sql server 数据库建立连接——想知道是否有人有一个可以将我的数据库信息插入其中的工作示例。
【问题讨论】:
-
这对我很有用。
我正在尝试找出将 hikaricp(JDBC 连接池)与 microsoft sql server 一起使用的最佳方法。据我所见,建议使用 DataSource 选项(就像我见过的大多数连接池一样)。但是,根据我看到的示例,我无法正确地与 sql server 数据库建立连接——想知道是否有人有一个可以将我的数据库信息插入其中的工作示例。
【问题讨论】:
确保您已采取以下步骤:
如果使用 maven,请确保您的 pom 文件中有以下依赖项(如果使用 JDK7/8):
<dependency>
<groupId>com.zaxxer</groupId>
<artifactId>HikariCP</artifactId>
<version>2.0.1</version>
<scope>compile</scope>
</dependency>
如果使用其他构建工具,请相应地更改资源 URL(如果没有其他选择,则只需从 maven 存储库下载 jar 文件)。
我相信您的 pom 文件中也需要 sqljdbc4.jar 文件(我可能对此要求有误,因此我可能会在再次确认后更新帖子)
在您的课程中导入以下内容以及其他参考资料:
import com.zaxxer.hikari.HikariConfig;
import com.zaxxer.hikari.HikariDataSource;
添加以下最终属性(或直接从配置文件加载):
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";
您可以像这样检索连接 URL:
public String getConnectionUrl() {
return url+this.serverName+":"+this.portNumber+";databaseName="+this.databaseName+";user="+this.userName+";password="+this.password+";selectMethod="+this.selectMethod+";";
}
然后,以下内容应为您提供获取连接所需的 DataSource:
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;
}
或
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
}
首选路线是将 HikariConfig 传递给 HikariDataSource 构造函数。您还可以从属性文件加载配置。
然后从数据源获取连接:
Connection con = null;
con = ds.getConnection(); //where ds is the dataSource retrieved from step 5
【讨论】: