JDBCドライバーを介してOracle DBに接続する
JDBCドライバーを使用してOracleデータベースに接続する方法を示すJDBCの例。
でテスト済み:
-
Java 8
-
Oracleデータベース19c
-
Java8用のOracleJDBCドライバー、
ojdbc8.jar
2. JDBC接続
Note
人気のあるORA-12505,
TNS:listener does not currently know of SIDを回避するために、{ORACLE_HOME}/network/admin/tnsnames.ora
でOracleSIDを検索します
2.1 Make a connection to the Oracle database.
JDBCExample.java
import java.sql.Connection; import java.sql.DriverManager; import java.sql.SQLException; public class JDBCExample { public static void main(String[] args) { // https://docs.oracle.com/javase/8/docs/api/java/sql/package-summary.html#package.description // auto java.sql.Driver discovery -- no longer need to load a java.sql.Driver class via Class.forName // register JDBC driver, optional since java 1.6 /*try { Class.forName("oracle.jdbc.driver.OracleDriver"); } catch (ClassNotFoundException e) { e.printStackTrace(); }*/ // Oracle SID = orcl , find yours in tnsname.ora try (Connection conn = DriverManager.getConnection( "jdbc:oracle:thin:@localhost:1521:orcl", "system", "Password123")) { if (conn != null) { System.out.println("Connected to the database!"); } else { System.out.println("Failed to make connection!"); } } catch (SQLException e) { System.err.format("SQL State: %s\n%s", e.getSQLState(), e.getMessage()); } catch (Exception e) { e.printStackTrace(); } } }
コンパイルして実行します。
C:\test> javac JDBCExample.java C:\test> java JDBCExample SQL State: 08001 No suitable driver found for jdbc:oracle:thin:@localhost:1521:orcl
2.2 Assume ojdbc8.jar
and JDBCExample.java
are stored in c: est
together. すべてを一緒にロードするための-cp
オプションを定義します。
> java -cp "c:\test\ojdbc8.jar;c:\test" JDBCExample Connected to the database!
3. Mavenプロジェクト
3.1 Sorry, due to Oracle license restriction, the Oracle JDBC driver is NOT available in the Maven central repository. このガイドに従って追加してください–How to add Oracle JDBC driver in your Maven local repository
3.2 Alternatively, defined a system scope to find the .jar
file with a specified system path.
pom.xml
com.oracle ojdbc 8 system d:/projects/ojdbc8.jar
ソースコードをダウンロード
$ git clone https://github.com/example/java-jdbc.git