
Java 애플리케이션을 SQL 데이터베이스와 연결
2017년부터 대학에서 Java를 공부하는 동안 두 개 이상의 수업에서 동료의 90%가 데이터베이스에 연결할 수 없고 모든 프로젝트가 메모리에 저장된 임시 상호 작용에만 의존한다는 것을 항상 알아차렸습니다.
그래서 오늘 이 기사를 통해 Java 애플리케이션을 JDBC를 통해 SQL 데이터베이스에 연결하기 위해 작성할 수 있는 각 행을 설명하는 심층 가이드를 제공하여 그들과 모든 커뮤니티를 도우려고 합니다.
JDBC 🤔?!
JDBC은 Java 데이터베이스 연결을 나타냅니다. JDBC는 JDBC 드라이버를 통해 모든 관계형 데이터베이스에 쿼리를 연결하고 실행하는 Java API입니다. JavaSE(Java Standard Edition)의 일부입니다.
Why Should We Use JDBC ?
Before JDBC, ODBC API was the database API to connect and execute the query with the database. But, ODBC API uses ODBC driver which is written in C language (i.e. platform dependent and unsecured). That is why Java has defined its own API (JDBC API) that uses JDBC drivers (written in Java language).
연결성 🪁 ?!
With this article, we use MySQL but almost steps are applied to all relational databases like PostgreSQL, SQLite, MariaDB, Oracle ...etc
먼저 엔진에서 이 sql 쿼리를 실행하여 데이터베이스를 설정하겠습니다.
CREATE DATABASE myjavadb;
USE myjavadb;
CREATE TABLE user(
id int(10),
name varchar(40),
age int(3)
);
그런 다음 자신의 IDE/편집기를 사용하여 Java 프로젝트를 만들고 다음 2단계에 따라 jdbc 커넥터 추가를 시작할 수 있습니다.
mysqlconnector.jar
) here . mysqlconnector.jar
커넥터 파일을 프로젝트에 붙여넣어 로드합니다.JRE/lib/ext folder
. 이제 2개의 클래스를 생성하여 연결 동작을 시작할 수 있습니다.
MySQLConnector
구성을 기반으로 데이터베이스 연결 URL을 생성합니다.public final class MySQLConnector {
private final static String dbHost = "localhost";
private final static String dbPort = "3306";
private final static String dbName = "myjavadb";
private final static String dbUsername = "root";
private final static String dbPassword = "mypassword";
public static String getConnectionURL() {
return String.format(
"jdbc:mysql//%s:%s/%s?user=%s&password=%s",
dbHost,
dbPort,
dbName,
dbUsername,
dbPassword
);
}
}
DBContext
데이터베이스 뒤의 모든 논리를 래핑합니다.import java.sql.*;
public class DBContext {
private Connection connection;
private Boolean connected;
public DBContext() {
this.connection = null;
this.connected = false;
}
public Boolean connect() throws SQLException, ClassNotFoundException {
// You can find the class name for any relational database with samll search on google.
// PostgreSQL example: https://jdbc.postgresql.org/documentation/81/load.html
Class.forName("mysql.jdbc.Driver");
// We use DriverManager.getConnection() to connect.
this.connection = DriverManager.getConnection(
MySQLConnector.getConnectionURL()
);
this.connected = true;
return this.connected;
}
public Boolean close() throws SQLException {
// Close the opened connection.
this.connection.close();
if (this.connection.isClosed()) {
this.connection = null;
this.connected = false;
}
return !this.connected;
}
}
문의 🐱💻 ?!
드디어 우리가 가장 섹시해졌습니다 🐱🏍! SQL 데이터베이스는 DML(데이터 조작 언어)을 통해 SQL CRUD 작업을 기반으로 데이터를 가져오거나 변경할 수 있는 기능을 제공합니다.

📍 You can learn more on DML and SQL through this ressource.
쿼리를 작성해야 하는 경우 명령문을 작성하고 실행해야 하지만 JDBC에는 2가지 유형의 명령문이 있습니다.
Summary:
If we want to pass params to the query and/or prevent the sql injection problems you should use
PreparedStatement
.
우리의 경우
PreparedStatement
;public class DBContext {
// ...
private PreparedStatement preparedStatement;
public DBContext() {
// ...
this.preparedStatement = null;
}
// ...
public PreparedStatement preparedQuery(String sqlQuery) throws SQLException {
// Not we can add our custom exception. Soon, I will write an article on it 😅!
if (!this.connected)
throw new SQLException();
this.preparedStatement = this.connection.prepareStatement(sqlQuery);
return this.preparedStatement;
}
// ...
}
그런 다음 DBContext 인스턴스를 만들고 다음과 같이 필요한 모든 매개변수를 주입합니다.
DBContext myDBContextInstance = new DBContext();
myDBContextInstance
.preparedQuery("SELECT * FROM ?;")
.setString(1, "users");
📍 You can check all params setter through the java offical web site.
이 단계에서 SQL 쿼리를 준비했지만 아직 데이터베이스와 상호 작용하지 않습니다!
그렇게 하려면 그것을 실행해야 합니다 ... 그러나 우리는 그것을 하는 2가지 방법이 있습니다;
1.
executeQuery
: SQL 쿼리 가져오기를 실행합니다( SELECT
).ResultSet result = myDBContextInstance
.preparedQuery("SELECT * FROM ?;")
.setString(1, "users")
.executeQuery();
while(result.next())
System.out.println(result.string('name'));
2.
executeUpdate
: 변형 SQL 쿼리를 실행하기 위해 ( INSERT
, UPDATE
, DELETE
).int result = myDBContextInstance
.preparedQuery("DELETE * FROM ? WHERE id=?;")
.setString(1, "users")
.setString(2, "1")
.executeUpdate();
System.out.println(result + " deleted!");
Note ⚠:
It would be better to improve the code by using patterns like the Singleton pattern to keep only one instance of the connection.