1. Statement
- JDBC로드 -> DB Connection 연결 -> 쿼리
/* JDBC 드라이브 로드 */
Class.forName("oracle.jdbc.OracleDriver");
/* DB연결 */
Connection conn = DriverManager.getConnection(
"jdbc:oracle:thin:@localhost:1521:orcl", "scott", "scott")
String query = "INSERT INTO USERINFO(NAME, ID, PASSWORD) VALUES(" + name + "," + id + "," + password + ")";
if(conn != null){
Statement stmt = conn.createStatement();
stmt.executeUpdate(query);
}
2. PreparedStatement
- JDBC로드 -> DB Connection 연결 -> 쿼리
/* JDBC 드라이브 로드 */
Class.forName("oracle.jdbc.OracleDriver");
/* DB연결 */
Connection conn = DriverManager.getConnection(
"jdbc:oracle:thin:@localhost:1521:orcl", "scott", "scott")
String query = "INSERT INTO USERINFO(NAME, ID, PASSWORD) VALUES(?, ?, ?)";
if(conn != null){
PreparedStatement pstmt = conn.prepareStatement(query);
pstmt.setString(1, name);
pstmt.setString(2, id);
pstmt.setString(3, password);
pstmt.executeUpdate();
}
※ PreparedStatement 가 훨씬 편함.
예제)
<%@page import="java.sql.PreparedStatement"%>
<%@page import="java.sql.DriverManager"%>
<%@page import="java.sql.Driver"%>
<%@page import="java.sql.Statement"%>
<%@page import="java.sql.Connection"%>
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8" errorPage="DBError.jsp"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title></title>
</head>
<body>
<%
request.setCharacterEncoding("UTF-8");
String name = request.getParameter("name");
String id = request.getParameter("id");
String password = request.getParameter("password");
if(name == null || id ==null || password == null){
throw new Exception("데이타를 입력하세요");
}
Connection conn = null;
PreparedStatement pstmt = null;
String DBurl = "jdbc:oracle:thin:@localhost:1521:orcl";
String DBuser = "scott";
String DBpassword = "scott";
try{
Class.forName("oracle.jdbc.OracleDriver");
conn = DriverManager.getConnection(DBurl, DBuser, DBpassword);
String query = "INSERT INTO USERINFO(NAME, ID, PASSWORD) VALUES(?, ?, ?)";
if(conn != null){
pstmt = conn.prepareStatement(query);
pstmt.setString(1, name);
pstmt.setString(2, id);
pstmt.setString(3, password);
pstmt.executeUpdate();
}
else {
throw new Exception("DB 연결 실패!");
}
}
finally{
pstmt.close();
conn.close();
}
response.sendRedirect("SubscriptionResult.jsp");
%>
</body>
</html>
'공부 > JSP' 카테고리의 다른 글
JSP_[계층형 게시판 알고리즘(펌)] (0) | 2012.11.07 |
---|---|
STRUTS_[struts ActionSupport 유효성 검사(Validation)] (0) | 2012.11.07 |
JSP_[JSTL 함수 라이브러리 사용] (0) | 2012.10.03 |
JSP_[자바 정적메소드를 EL(익스프레션언어)함수로 등록하는 방법] (0) | 2012.09.19 |
JSP_[자바Bean의 프로퍼티 가져와서 EL 출력하는 방법] (0) | 2012.09.19 |