>> 위와 같이 one이라는 데이터베이스에 book이라는 테이블을 생성한 후 간단한 값을 입력한다.
import java.sql.*;
public class JDBC {
public static void main(String[] args) {
// 1.드라이브 검색
try {
Class.forName("com.mysql.jdbc.Driver");
} catch (ClassNotFoundException ce) {
System.out.println("드라이브를 찾을 수 없습니다.");
}
// 2. Connection 객체
try {
Connection conn = DriverManager.getConnection(
"jdbc:mysql://localhost:3306/One", "root", "1234");
//프로토콜:서브프로토콜://DBMS주소:포트번호/데이타베이스
// 3. Statement or PreparedStatement
String query = "select * from book";
Statement stmt = conn.createStatement(); //정적쿼리
String query2 = query + " where num = ?";
PreparedStatement pstmt =
conn.prepareStatement(query2); //동적쿼리
// 4. ResultSet 결과 얻기
ResultSet rs = stmt.executeQuery(query);
pstmt.setInt(1, 10);
ResultSet rs2 = pstmt.executeQuery();
// 5. 출력하기
System.out.println("ALL!!");
while(rs.next()){
int num = rs.getInt(1);
String id = rs.getString(2);
String name = rs.getString(3);
System.out.println(num + " : " + id + " : " + name);
}
System.out.println("id가 10인 칼럼");
while(rs2.next()){
int num = rs2.getInt(1);
String id = rs2.getString(2);
String name = rs2.getString(3);
System.out.println(num + " : " + id + " : " + name);
}
// 6. 닫기
rs.close();
rs2.close();
stmt.close();
pstmt.close();
conn.close();
} catch (SQLException se) {
System.out.println("DB 연동 오류 : " + se.getLocalizedMessage());
}
}
}
>> 결과
'백업' 카테고리의 다른 글
[MVC패턴] 회원가입 페이지 만들기 (0) | 2014.08.10 |
---|---|
[MVC패턴] 기초 (0) | 2014.08.10 |
[환경설정] 환경설정 (0) | 2014.08.05 |
[입출력] 객체 입출력 (0) | 2014.08.05 |
[입출력] 텍스트 입력 (0) | 2014.08.05 |