JDBC sample 프로그램입니다

by 관리자 posted Oct 25, 2007
기본적인 JDBC 응용 샘플입니다.

수행하시려면 서버 주소/포트/DB명등을 고치시고 해보세요.
프로그램 구조는 클래스를 만들고
Prepare문을 통해 질의를 수행하고
Rollback으로 수행을 취소시키는 구조입니다.


import java.util.*;
import java.sql.*;

public class basic {

public static Connection connect() {
Connection conn = null;
try {
Class.forName("cubrid.jdbc.driver.CUBRIDDriver");
conn = DriverManager.getConnection("jdbc:cubrid:192.168.1.1:30000:testdb:dba::","dba","");
conn.setAutoCommit (false) ;
} catch ( Exception e ) {
System.err.println("SQLException : " + e.getMessage());
}
return conn;
}

public static void printdata(ResultSet rs) {
try {
ResultSetMetaData rsmd = null;

rsmd = rs.getMetaData();
int numberofColumn = rsmd.getColumnCount();

while (rs.next ()) {
for(int j=1; j<=numberofColumn; j++ )
System.out.print(rs.getString(j) + " " );
System.out.println("");
}
} catch ( Exception e ) {
System.err.println("SQLException : " + e.getMessage());
}
}

public static void main(String[] args) throws Exception {
Connection conn = null;
Statement stmt = null;
ResultSet rs = null;
PreparedStatement preStmt = null;

try {
conn = connect();

stmt = conn.createStatement();
stmt.executeUpdate("create class xoo ( a int, b int, c char(10))");

preStmt = conn.prepareStatement("insert into xoo values(?,?,''''100'''')") ;
preStmt.setInt (1, 1) ;
preStmt.setInt (2, 1*10) ;
int rst = preStmt.executeUpdate () ;

rs = stmt.executeQuery("select a,b,c from xoo" );

printdata(rs);

conn.rollback();
stmt.close();
conn.close();
} catch ( Exception e ) {
conn.rollback();
System.err.println("SQLException : " + e.getMessage());
} finally {
if ( conn != null ) conn.close();
}
}
}