카테고리 없음
Properties와FlieReader 로 Connection얻기_210525(화)
docc
2021. 7. 25. 12:39
Properties : Map 계열 , key 와 value 가 String 인 class
>> config.properties
driver = com.mysql.cj.jdbc.Driver
url = jdbc:mysql://localhost:3306/sys?useUnicode=true
id = root
passwd = 1234
>> ConnectionUtil.java
package 연결유틸;
import java.io.*;
import java.sql.*;
import java.net.URLDecoder;
import java.util.Properties;
import javax.annotation.Resources;
public class ConnectionUtil {
public static Connection getConnection() {
Connection 연결 = null;
try {
Properties info = new Properties();
// 1번째 방법: Class(본인클래스에가져오기) 와 FileReader() 사용
// String file = ConnectionUtil.class.getResource("D://javaclass//ws1//연결유틸//src//config/DB.properties").getPath();
// file = URLDecoder.decode(file, "uft-8"); //파일명이 한글이여서 주소가 깨지는게 아니라면 딱히 안해도 됨.
// System.out.println(file);
// 2번째 방법: File 과 FileReader() 사용
File file = new File("D:\\javaclass\\ws1\\board3_nvc0\\src\\config\\DB.properties");
// 공통부분
info.load(new FileReader(file));
Class.forName(info.getProperty("driver"));
연결 = DriverManager.getConnection(info.getProperty("url"),
info.getProperty("id"),
info.getProperty("passwd"));
}catch(Exception e) {
e.printStackTrace();
}
return 연결;
}
public static void close(Connection 연결) {
try {
연결.close();
} catch (SQLException sqlE) {
sqlE.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
}
}
>> 게시물DAO.java ( 메서드 바뀐 부분 확인: Connection 얻기가 쉬워졌다. )
public class 게시물DAO {
public void 저장한다(게시물 새게시물) {
try {
Connection DB연결관리자 = ConnectionUtil.getConnection();
Statement 명령전달자 = DB연결관리자.createStatement();
String 삽입SQL = "insert into 게시물(제목,내용) values('" + 새게시물.get제목() + "','" + 새게시물.get내용() + "');";
명령전달자.executeUpdate(삽입SQL); // 명령전달자가 보낸다.
DB연결관리자.close();
} catch (Exception e) {
e.printStackTrace();
}
}