jdbc
데이터베이스 연결 만들기
수색…
통사론
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.sql
과 javax.sql
이라는 두 개의 패키지로 제공됩니다.
JDBC는 데이터베이스 상호 작용을 Connections
및 Drivers
정의합니다.
Driver
는 데이터베이스와 상호 작용하고 연결을 열고 관리하기위한 단순화 된 인터페이스를 제공합니다. 대부분의 데이터베이스 서버 종류 (PostgreSQL, MySQl 등)에는 해당 서버에 특정한 설정, 분해 및 변환을 처리하는 고유 한 Drivers
가 있습니다. Drivers
는 일반적으로 직접 액세스 할 수 없습니다. 대신 DriverManager
객체가 제공하는 인터페이스가 대신 사용됩니다.
DriverManager
객체는 본질적으로 JDBC의 핵심입니다. Connections
을 작성하기 위해 데이터베이스와 관련없는 (대부분) 데이터베이스 인터페이스를 제공 Connections
. 이전 버전의 JDBC API의 경우 DeviceManager
가 해당 데이터베이스 유형에 대한 연결을 생성하기 전에 데이터베이스 별 Drivers
를로드해야했습니다.
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>
은 드라이버 또는 데이터베이스를 식별합니다 (예 : postgresql
, mysql
, firebirdsql
등). <subname>
은 서브 프로토콜마다 다릅니다.
특정 url 서브 프로토콜 및 드라이버 형식에 대한 데이터베이스 및 JDBC 드라이버의 문서를 확인해야합니다.
jdbc:somedb://localhost/foobar
: url을 사용하여 데이터베이스에 대한 연결을 만드는 간단한 예제
try (Connection connection = DriverManager.getConnection(
"jdbc:somedb://localhost/foobar", "anna", "supersecretpassword")) {
// do something with connection
}
여기에 try-with-resources 를 사용하기 때문에 예외가 발생하더라도 연결이 자동으로 닫힙니다.
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();
}
JDBC 4.0 (Java 6)은 자동 드라이버로드 개념을 도입했습니다. Java 5 또는 이전 버전 또는 JDBC 4 지원을 구현하지 않는 이전 JDBC 드라이버를 사용하는 경우 드라이버를 명시 적으로로드해야합니다.
Class.forName("org.example.somedb.jdbc.Driver");
이 줄은 연결이 이루어지기 전에 프로그램에서 적어도 한 번 발생해야합니다.
JDBC 4.0을 사용하는 자바 6 이상에서도 명시 적으로 드라이버를로드해야 할 수도 있습니다. 예를 들어 드라이버가 컨테이너에로드되지 않았지만 웹 응용 프로그램의 일부로 웹 응용 프로그램에있는 경우입니다.
또는 연결할 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
}
이전 Java / JDBC 버전 :
// 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는 ODBC
를 사용하지 않고 Access 데이터베이스에서 읽고 쓸 수있는 순수 Java JDBC
드라이버입니다. Jackcess
와 HSQLDB
Jackcess
두 개의 다른 패키지를 사용하여 이러한 작업을 수행합니다.
이 *을 설정 한 후에, 우리는 다음과 같은 코드를 사용하여 .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");