Search

Java JDBC - MySQL ์—ฐ๊ฒฐ

Java JDBC - MySQL ์—ฐ๊ฒฐ

MySQL JDBC ๋“œ๋ผ์ด๋ฒ„ ๋‹ค์šด๋กœ๋“œ

ํ”„๋กœ์ ํŠธ์— JDBC ๋“œ๋ผ์ด๋ฒ„ ์ถ”๊ฐ€

โ€ข
[ํ”„๋กœ์ ํŠธ ์šฐํด๋ฆญ]
โ€ข
[Build Path] > [Configure Build Path]
โ—ฆ
[Libraries ํƒญ] > [Add JARsโ€ฆ] or [Add External JARsโ€ฆ]
โ—ฆ
mysql-connector-j-8.1.0 ์„ ํƒ

์‹œ์ž‘์ฝ”๋“œ

โ€ข
JDBConnection.java
import java.sql.Connection; import java.sql.DriverManager; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.Statement; public class JDBConnection { public Connection con; // ์—ฐ๊ฒฐ๋œ ๋“œ๋ผ์ด๋ฒ„์— SQL์„ ์š”์ฒญํ•  ๊ฐ์ฒด๋ฅผ ์ƒ์„ฑํ•˜๋Š” ํด๋ž˜์Šค public Statement stmt; // SQL ์‹คํ–‰ ์š”์ฒญ์„ ํ•˜๋Š” ํด๋ž˜์Šค public PreparedStatement psmt; // Statement ์—์„œ ? ํŒŒ๋ผ๋ฏธํ„ฐ ํ™•์žฅ๊ธฐ๋Šฅ์„ ์ถ”๊ฐ€๋กœ ์ œ๊ณตํ•˜๋Š” ํด๋ž˜์Šค public ResultSet rs; // SQL ์‹คํ–‰ ๊ฒฐ๊ณผ๋ฅผ ๋ฐ›์•„์˜ค๋Š” ํด๋ž˜์Šค // ๊ธฐ๋ณธ ์ƒ์„ฑ์ž public JDBConnection() { // JDBC ๋“œ๋ผ์ด๋ฒ„ ๋กœ๋“œ // MySQL try { // mysql-connector-j.xxx.jar ๋“œ๋ผ์ด๋ฒ„์˜ ํด๋ž˜์Šค๋ฅผ ๋กœ๋“œํ•œ๋‹ค. Class.forName("com.mysql.cj.jdbc.Driver"); // DB์— ์—ฐ๊ฒฐ // - ์—ฐ๊ฒฐ์— ํ•„์š”ํ•œ ์ •๋ณด : URL, id, pw // URL : jdbc:mysql://๋„๋ฉ”์ธ:[PORT]/[์Šคํ‚ค๋งˆ]?์˜ต์…˜ํŒŒ๋ผ๋ฏธํ„ฐ // * ๋‚ด PC์˜ IP์ฃผ์†Œ : localhost : 127.0.0.1 // * 3306 : MySQL ๋ฐ์ดํ„ฐ๋ฒ ์ด์Šค์˜ ๊ธฐ๋ณธ ํฌํŠธ String url = "jdbc:mysql://127.0.0.1:3306/aloha?serverTimezone=Asia/Seoul&allowPublicKeyRetrieval=true&useSSL=false"; String id = "aloha"; String pw = "123456"; // ์ž๋ฐ” ํ”„๋กœ๊ทธ๋žจ์—์„œ JDBC ๋“œ๋ผ์ด๋ฒ„๋ฅผ ์—ฐ๊ฒฐ์‹œ์ผœ์ฃผ๋Š” ํด๋ž˜์Šค // getConnection() ๋ฉ”์†Œ๋“œ๋กœ DB์— ์—ฐ๊ฒฐ ์š”์ฒญํ•˜๊ณ  ์ƒ์„ฑ๋œ Connection ๊ฐ์ฒด๋ฅผ ๋ฐ˜ํ™˜๋ฐ›๋Š”๋‹ค. con = DriverManager.getConnection(url, id, pw); System.out.println("DB ์—ฐ๊ฒฐ ์„ฑ๊ณต"); } catch (Exception e) { System.err.println("DB ์—ฐ๊ฒฐ ์‹คํŒจ"); e.printStackTrace(); } } }
Java
๋ณต์‚ฌ
โ€ข
Main.java
import DAO.JDBConnection; public class Main { public static void main(String[] args) { JDBConnection connection = new JDBConnection(); } }
Java
๋ณต์‚ฌ