サーチ…


構文

  • DB_URL = "jdbc:DBMS:// DB_HOST:DB_PORT / DB_NAME"

  • DBMS:データベースベースのドライバマネージャー、これは任意のDBMS(mysql、oracle、postgresql、sqlite、...)、mysqlの例: "com.mysql.jdbc.Driver"

  • DB_HOST:データベースのベースホスト、データベースのIPアドレス例:10.6.0.1、デフォルトはlocalhostまたは127.0.0.1です。

  • DB_PORT:データベースポート、すべてのDBMSには敗北ポートがあります。例:mysql = 3306、postegesql = 5432

  • DB_NAME:データベースの名前

  • 接続するには、クラスオブジェクトへの参照を取得する必要があります。

  • Class.forName(DRIVER);

  • データベースに接続するには、接続を作成する必要があります

  • java.sql.Connection con = DriverManager.getConnection(DB_URL、DB_USER_NAME、DB_PASSWORD);

  • DB_USER_NAME:あなたのデータベースのユーザ名

  • DB_PASSWORD:データベースのパスワード

はじめに(SQL)

Java 6以降、JavaでSQLベースのデータベースにアクセスするには、JDBC(Java DataBase Connectivity)APIを使用することをお勧めします。

このAPIは、 java.sqljavax.sql 2つのパッケージになっていjava.sql

JDBCは、データベースの相互作用をConnectionsDrivers観点から定義します。

Driverはデータベースとやりとりし、接続を開いて管理するための簡単なインターフェイスを提供します。ほとんどのデータベースサーバーの種類(PostgreSQL、MySQlなど)には、独自のDrivers 、そのサーバーに固有のセットアップ、ティアダウン、および変換を処理します。 Driversは通常直接アクセスされません。代わりに、 DriverManagerオブジェクトによって提供されるインタフェースが代わりに使用されます。

DriverManagerオブジェクトは本質的にJDBCのコアです。これは、 Connectionsを作成するための(ほとんどの)データベースに依存しないインタフェースを提供します。古いバージョンのJDBC APIの場合、 DeviceManagerがそのデータベースタイプへの接続を作成するには、データベース固有のDriversをロードするDeviceManagerがありました。

Connectionは、名前が示すように、データベースへのオープンな接続の表現です。 Connectionsはデータベースに依存しないもので、 DriverManagerによって作成され、提供されます。それらは、一般的なクエリ型のための多くの「ショートカット」メソッドと、未処理のSQLインタフェースを提供します。

接続(および文)の使用

Connectionを取得したら、主にStatementオブジェクトの作成に使用します。 Statementsは単一のSQLトランザクションを表します。それらはクエリを実行し、結果があれば検索します。いくつかの例を見てみましょう:

public void useConnection() throws SQLException{


    Connection conn = getConnection();

    //We can use our Connection to create Statements
    Statement state = conn.getStatement();

    //Statements are most useful for static, "one-off" queries
    
    String query = "SELECT * FROM mainTable";
    boolean sucess = state.execute(query);
    
    //The execute method does exactly that; it executes the provided SQL statement, and returns true if the execution provided results (i.e. was a SELECT) and false otherwise.

    ResultSet results = state.getResultSet();
    
    //The ResultSet object represents the results, if any, of an SQL statement.
    //In this case, the ResultSet contains the return value from our query statement.
    //A later example will examine ResultSets in more detail.

    ResultSet newResults = state.executeQuery(query)
    
    //The executeQuery method is a 'shortcut' method. It combines the execute and getResultSet methods into a single step.
    //Note that the provided SQL query must be able to return results; typically, it is a single static SELECT statement.
    //There are a number of similar 'shortcut' methods provided by the Statement interface, including executeUpdate and executeBatch

    //Statements, while useful, are not always the best choice. 
    
    String newQuery = "SELECT * FROM mainTable WHERE id=?";
    PreparedStatement prepStatement = conn.prepareStatement(newQuery);

    //PreparedStatements are the prefed alternative for variable statements, especially ones that are going to be executed multiple times

    for(int id:this.ids){

        prepStatement.setInt(1,id);
        //PreparedStatements allow you to set bind variables with a wide variety of set methods.
        //The first argument to any of the various set methods is the index of the bind variable you want to set. Note that this starts from 1, not 0. 

        ResultSet tempResults = prepStatement.executeQuery()
        //Just like Statements, PreparedStatements have a couple of shortcut methods. 
        //Unlike Statements, PreparedStatements do not not take a query string as an argument to any of their execute methods.
        //The statement that is executed is always the one passed to the Connector.prepareStatement call that created the PreparedStatement
    }

}

java.sql.DriverManagerを使用した接続の作成

java.sql.DriverManagerを使用して接続するには、データベースに接続するためのJDBC URLが必要です。 JDBCのURLはデータベース固有のものですが、すべての形式です

jdbc:<subprotocol>:<subname>

<subprotocol>はドライバまたはデータベースを指定します(たとえば、 postgresqlmysqlfirebirdsqlなど)。 <subname>はサブプロトコル固有です。

特定のURLサブプロトコルとドライバのフォーマットについては、データベースとJDBCドライバのドキュメントを確認する必要があります。

url jdbc:somedb://localhost/foobarを使用してデータベースへの接続を作成する簡単な例:

try (Connection connection = DriverManager.getConnection(
        "jdbc:somedb://localhost/foobar", "anna", "supersecretpassword")) {
    // do something with connection
}

ここではtry-with-resourcesを使用しているため、例外が発生しても接続が自動的に閉じられます。

4.0

Java 6(JDBC 4.0)以前のバージョンでは、リソースは試用できません。これらのバージョンでは、 finallyブロックを使用して明示的に接続を閉じる必要があります:

Connection connection = DriverManager.getConnection(
        "jdbc:somedb://localhost/foobar", "anna", "supersecretpassword");
try {
    // do something with connection
} finally {
    // explicitly close connection
    connection.close();
}
4.0

JDBC 4.0(Java 6)では自動ドライバロードの概念が導入されました。 Java 5以前、またはJDBC 4サポートを実装していない古いJDBCドライバを使用する場合は、明示的にドライバをロードする必要があります。

Class.forName("org.example.somedb.jdbc.Driver");

この行は、接続が行われる前に、プログラム内で(少なくとも)1回発生する必要があります。

JDBC 4.0を使用するJava 6以上であっても、明示的にドライバをロードする必要があります。たとえば、ドライバがコンテナにロードされていないWebアプリケーションの一部である場合などです。

また、接続するPropertiesオブジェクトを提供することもできProperties

Properties props = new Properties();
props.setProperty("user", "anna");
props.setProperty("password", "supersecretpassword");
// other, database specific, properties
try (Connection connection = DriverManager.getConnection(
        "jdbc:somedb://localhost/foobar", props)) {
    // do something with connection
}

あるいは、たとえデータベースがユーザー名とパスワードを必要としない場合など、プロパティなしでも:

try (Connection connection = DriverManager.getConnection(
        "jdbc:somedb://localhost/foobar")) {
    // do something with connection
}

MySQLへの接続の作成

MySQLに接続するには、MySQL Connector / Jドライバを使用する必要があります。 http://dev.mysql.com/downloads/connector/j/からダウンロードするか、Mavenを使用することができます:

<dependency>
    <groupId>mysql</groupId>
    <artifactId>mysql-connector-java</artifactId>
    <version>5.1.39</version>
</dependency>

MySQL基本JDBC URLは次のとおりです。

jdbc:mysql://<hostname>[:<port>]/<database>[?<propertyName>=<propertyValue>[&<propertyName>=<propertyValue>]...]

場所:

キー説明
<hostname> MySQLサーバのホスト名 localhost
<port> MySQLサーバのポート(オプション、デフォルト:3306) 3306
<database> データベースの名前 foobar
<propertyName> 接続プロパティの名前 useCompression
<propertyValue> 接続プロパティの値 true

サポートされているURLは上記よりも複雑ですが、これはほとんどの「通常の」ニーズには十分です。

接続するには:

try (Connection connection = DriverManager.getConnection(
        "jdbc:mysql://localhost/foobardb", "peter", "nicepassword")) {
    // do something with connection
}
4.0

古いJava / JDBCバージョンの場合:

4.0
// Load the MySQL Connector/J driver
Class.forName("com.mysql.jdbc.Driver");
Connection connection = DriverManager.getConnection(
        "jdbc:mysql://localhost/foobardb", "peter", "nicepassword");
try {
    // do something with connection
} finally {
  // explicitly close connection
  connection.close();
}

UCanAccessを使用したMicrosoft Accessデータベースへの接続

UCanAccessは、純粋なJava JDBCドライバであり、 ODBCを使用せずにAccessデータベースに対して読み書きを行うことができODBC 。これらのタスクを実行するには、 JackcessHSQLDB 2つのパッケージを使用します。

*を設定したら、次のようなコードを使用して.accdbファイルと.mdbファイルのデータを処理できます。

import java.sql.*;

Connection conn=DriverManager.getConnection("jdbc:ucanaccess://C:/__tmp/test/zzz.accdb");
Statement s = conn.createStatement();
ResultSet rs = s.executeQuery("SELECT [LastName] FROM [Clients]");
while (rs.next()) {
    System.out.println(rs.getString(1));
}

*詳細については、次の質問を参照してください:

ODBCを使用しないJavaからAccessデータベースを操作する

Oracle JDBC接続

ドライバ:

注:ドライバはMaven Centralに含まれていません!)

ドライバクラスの初期化:

    Class.forName("oracle.jdbc.driver.OracleDriver");

接続URL

SIDを使用した古い形式

"jdbc:oracle:thin:@<hostname>:<port>:<SID>"

新しい形式、サービス名付き

"jdbc:oracle:thin:@//<hostname>:<port>/<servicename>"

エントリのようなTNSnames

"jdbc:oracle:thin:@(DESCRIPTION=(ADDRESS=(PROTOCOL=TCPS)(HOST=<hostname>)(PORT=<port>))"
    +"(CONNECT_DATA=(SERVICE_NAME=<servicename>)))"

フェールオーバーのためのRACクラスタ接続文字列

"jdbc:oracle:thin:@(DESCRIPTION=(ADDRESS_LIST=(LOAD_BALANCE=OFF)(FAILOVER=ON)"
    +"(ADDRESS=(PROTOCOL=TCP)(HOST=<hostname1>)(PORT=<port1>))"
    +"(ADDRESS=(PROTOCOL=TCP)(HOST=<hostname2>)(PORT=<port2>)))"
    +"(CONNECT_DATA=SERVICE_NAME=<servicename>)(SERVER=DEDICATED)))"

connection = DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:orcl", "HR", "HRPASS");


Modified text is an extract of the original Stack Overflow Documentation
ライセンスを受けた CC BY-SA 3.0
所属していない Stack Overflow