Java에서 SQL문을 실행하기 위한 Java API
String driverName ="oracle.jdbc.driver.OracleDriver";
Class.forName(driverName); //드라이버 로드
String jdbcURL= "jdbc:oracle:thin:@127.0.0.1:1521:XE"; //connection
String userName ="dclub";
String userPW ="dclub";
Connection con = DriverManager.getConnection(jdbcURL, userName, userPW);
String query ="select sysdate from dual";
PreparedStatement pstmt = con.prepareStatement(query);
ResultSet rs = pstmt.executeQuery();
rs.next();
result = rs.getString(1);
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@ page import= "org.zerock.dao.*" %>
<%
TimeDAO dao = new TimeDAO();
String str = dao.getTime();
%>
package org.zerock.dao;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
public class TimeDAO {
//DB타입변수는 반드시 IV로 만들지마라, 그리고 Close
public String getTime()throws Exception {
// 오라클 : oracle.jdbc.driver.OracleDriver
String driverName ="oracle.jdbc.driver.OracleDriver";
// 오라클 : jdbc:oracle:thin@HOST:PORT:SID
String jdbcURL= "jdbc:oracle:thin:@127.0.0.1:1521:XE"; //connection
String userName ="dclub";
String userPW ="dclub";
//; 주의
String query ="select sysdate from dual"; //statement객체를 생성 및 질의수행하기위한 쿼리문
//dual은 sysdate를 테스트하는 용도
String result = null;
Class.forName(driverName); //드라이버 로드
try (Connection con = DriverManager.getConnection(jdbcURL, userName, userPW); //connection얻기
PreparedStatement pstmt = con.prepareStatement(query); //statement생성
ResultSet rs = pstmt.executeQuery(); //select하면 항상 ResultSet
){
System.out.println(con);
rs.next(); //위에서 한row내려오려고
result = rs.getString(1); //칼럼 1부터 시작함 = 첫번째 칼럼읽어옴
}catch(Exception e) {
throw e;
}
return result;
}
}
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@ page import= "org.zerock.dao.*" %>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
<%
TimeDAO dao = new TimeDAO();
String str = dao.getTime();
%>
<%=str %>
</body>
</html>