0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

Webアプリでのtry with resources文

Last updated at Posted at 2019-02-17

経緯

javaのtry with resources文を書こうとして
sqlserverを使うのでmssql-jdbc-7.0.0.jre8.jarをインポートした。

この時以下のコードがエラーに

dbConnect.java
try(Connection connection = DriverManager.getConnection(url)) {
}

と書くと「No suitable driver found for jdbc:sqlserver://〜」とエラーが出ました。

エラーを調べたところ、Class.forNameでドライバを指定するようにと出たので、
以下のコードに修正。

dbConnect.java
try{
//JDBCドライバを指定(JDBC3.0以下)
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
Connection connection = DriverManager.getConnection(url); 
}

修正してエラーを無くしたのですが、これではtry with resources文が使用できていないので、どうにか最初のコードで動かす方法を探した。

解決策

原因はtomcatのクラスパスにjdbcが指定されていない為、Class.forNameなしではjdbcまでのパスがわからないことが原因だった。

eclipseを使用していたので、「tomcat>実行の構成>クラスパス>外部JARの選択」を選択し、libの下にインポートしたjdbcのjarにパスを通すことで正常終了した。

その後

Azureが好きなので、AppService上にデプロイしたが、tomcatのクラスパスに追加する方法がわからないので、分かったら追記する

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?