JDBC 프로그래밍
// 1단계 : import java.sql.*;
import java.sql.*;
public class JDBCTest {
public static void main(String[] args) {
String JDBC_DRIVER = "com.mysql.jdbc.Driver";
String JDBC_URL =
"jdbc:mysql://localhost:3306/mydb?uniCode=true&characterEncoding=euckr";
String DBUSER = "root";
String DBUSER_PASS = "pass";
Connection conn = null;
Statement st = null;
ResultSet rs = null;
try {
// 2단계 : 드라이버 로딩
Class.forName(JDBC_DRIVER);
System.out.println("드라이버 로딩 성공");
// 3단계 : Connection 객체를 생성한다.
conn = DriverManager.getConnection(JDBC_URL,
DBUSER, DBUSER_PASS);
System.out.println("연결 성공");
// 4단계 : Statement객체를 생성한다.
st = conn.createStatement();
System.out.println("명령 준비 성공");
String sql = "select * from member";
// 5단계 : 결과가 있다면 ResultSet 객체를 생성한다.
rs = st.executeQuery(sql);
System.out.println("결과 얻었음");
while(rs.next()) {
String userid = rs.getString("userid");
String userpass = rs.getString("userpass");
System.out.println(
"userid="+userid+",userpass="+userpass);
}//while
} catch (Exception e) {
e.printStackTrace();
} finally {
// 6단계 : 모든 객체를 닫는다.
if(rs != null)
try {
rs.close();
} catch (SQLException e) {
e.printStackTrace();
}
if(st != null)
try {
st.close();
} catch (SQLException e) {
e.printStackTrace();
}
if(conn != null)
try {
conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
}//finally
}// main
}// end
[출처] JDBC 프로그래밍 6단계|작성자 메멘토