DB/Maria DB
properties를 이용한 MariaDB 연결
라롸
2020. 2. 17. 16:37
기본적인 연결방법 코드
String sql = "";
Connection conn;
Statement stmt;
ResultSet rs;
try{
Class.forName("org.mariadb.jdbc.Driver");
conn = DriverManager.getConnection("jdbc:mysql://서버명:3306/디비명", "유저명", "비밀번호");
stmt = conncreateStatement();
sql = "select * from 테이블명";
rs = stmt.executeQuery(sql);
//결과 출력
while(rs.next()){
System.out.println(rs.getString(1) + " " + ... ... + rs.getString(10));
}
}catch(Exception e){
e.printStackTrace();
} finnally{
try {
if(rs != null) rs.close();
if(stmt != null) stmt.close();
if(conn != null) conn.close();
}catch (Exception e2) {
e2.printStackTrace();
}
}
위와 같이 코딩할 경우 유저명과 비밀번호가 그대로 노출되게 된다.
따라서 비밀번호를 숨기기 위해 시큐어 코딩을 할 필요가 있다.
자세한 가이드는 (https://www.kisa.or.kr/public/laws/laws3_View.jsp?mode=view&p_No=259&b_No=259&d_No=55&ST=T&SV=) 를 따라서 하면 된다.
가장 간단하게 시큐어코딩을 하려면 각각의 정보를 따로 properties에 저장하고 이 파일을 불러오는 방식으로 한다.
- properties 파일 내용
driver=org.mariadb.jdbc.Driver
url=jdbc:mysql://서버명:3306/디비명
user=유저명
passwd=비밀번호
- properties 파일 내용을 적용한 코드
Connection conn;
Statement stmt;
ResultSet rs;
Properties properties = new Properties();
String sql = "";
try {
properties.load(new FileInputStream("properties파일의 주소")); //원래는 properties 파일 암호화 후 사용
Class.forName(properties.getProperty("driver"));
conn = DriverManager.getConnection(properties.getProperty("url"),properties.getProperty("user"),properties.getProperty("passwd"));
stmt = conn.createStatement();
}catch (Exception e) {
System.out.println("에러 : " + e.getMessage());
} finally {
try {
if(rs != null) rs.close();
if(stmt != null) stmt.close();
if(conn != null) conn.close();
} catch (Exception e2) {
System.out.println("에러2 : " + e2.getMessage());
}
}