ドライバの読み込み

Before you can connect to a database, you need to load the driver. There are two methods available, and it depends on your code to the best one to use.

データベースに接続する前に、ドライバを読み込まなくてはいけません。 2 つの方法をとることができ、どちらが最適なのかは作成するコードに依 存します。

In the first method, your code implicitly loads the driver using the Class.forName() method. For Postgres, you would use:

最初の方法では、コードの中で明示的に Class.forName() メソッドを使って ドライバを読み込みます。Postgres の場合は、 次のように使います。

Class.forName("postgresql.Driver");
This will load the driver, and while loading, the driver will automatically register itself with JDBC. これでドライバが読み込まれます。読み込まれると、ドライバは自動的に自 分自身を JDBC に登録します。

Note: The forName() method can throw a ClassNotFoundException, so you will need to catch it if the driver is not available.

注意: forName() は ClassNotFoundException を投げま すので、ドライバが利用できなかった場合にこの例外を捕らえなければなりま せん。

This is the most common method to use, but restricts your code to use just Postgres. If your code may access another database in the future, and you don't use our extensions, then the second method is advisable.

これは最も一般的に使われる方法ですが、そのコードは Postgres だけでしか使えなくなります。今後 他のデータベースにアクセスする可能性があり、また、拡張機能を使用しな いのならば、2 番目の方法を勧めます。

The second method passes the driver as a parameter to the JVM as it starts, using the -D argument.

2 番目の方法は、-D 引数を使用して、ドライバをパラメータとして JVM の 起動時に渡すことです。

Example:

例:

% java -Djdbc.drivers=postgresql.Driver example.ImageViewer

In this example, the JVM will attempt to load the driver as part of it's initialisation. Once done, the ImageViewer is started.

この例では、JVM はその初期化段階の一部としてドライバの読み込みを 試みます。読み込みが完了したところで、ImageViewer が起動します。

Now, this method is the better one to use because it allows your code to be used with other databases, without recompiling the code. The only thing that would also change is the URL, which is covered next.

さて、コードをコンパイルし直すことなく他のデータベースにも使うことが できますので、この方法は前者よりも優れています。次節で示す URL のみを 変更することになります。

One last thing. When your code then tries to open a Connection, and you get a No driver available SQLException being thrown, this is probably caused by the driver not being in the classpath, or the value in the parameter not being correct.

最後に、コード内で接続を開こうとした時に No driver available が投げられた場合、大抵、ド ライバがクラスパスにないこと、もしくは、パラメータの値が正しくない ことが原因です。