다음은 JDBC 드라이버를 통해 CUBRID에 접속하여 데이터를 조회, 삽입하는 것을 간단하게 구성한 예제이다. 예제를 실행하려면 먼저 접속하고자 하는 데이터베이스와 CUBRID 브로커가 구동되어 있어야 한다. 예제에서는 설치 시 자동으로 생성되는 demodb 데이터베이스를 사용한다.
CUBRID에 접속하기 위해서는 Class의 forName() 메소드를 사용하여 JDBC 드라이버를 로드해야 한다. 자세한 내용은 CUBRID JDBC 드라이버를 참고한다.
Class.forName("cubrid.jdbc.driver.CUBRIDDriver");
JDBC 드라이버를 로드한 후 DriverManager의 getConnection() 메소드를 사용하여 데이터베이스와 연결한다. Connection 객체를 생성하기 위해서는 데이터베이스의 위치를 기술하기 위한 URL, 데이터베이스의 사용자 이름, 암호 등의 정보가 지정되어야 한다. 자세한 내용은 연결 설정을 참고한다.
String url = "jdbc:cubrid:localhost:30000:demodb:::";
String userid = "dba";
String password = "";
Connection conn = DriverManager.getConnection(url,userid,password);
접속된 데이터베이스에 질의문을 전달하고 실행시키기 위하여 Statement, PrepardStatement, CallableStatement 객체를 생성한다. Statement 객체가 생성되면, Statement 객체의 executeQuery() 메소드나 executeUpdate() 메소드를 사용하여 질의문을 실행한다. next() 메소드를 사용하여 ExecuteQuery() 메소드의 결과로 반환된 ResultSet의 다음 행을 처리할 수 있다. 보다 자세한 내용은 JDBC API를 참고한다.
각 객체에 대해 close() 메소드를 수행하여 데이터베이스와의 연결을 해제할 수 있다.
아래는 demodb에 접속하여 테이블을 생성하고 prepared statement로 질의문을 수행한 후 질의를 롤백시키는 예제코드이며, getConnection() 메소드의 인자값을 적절하게 수정하여 실습할 수 있다.
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:localhost:30000:demodb::","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();
}
}
}
다음은 CUBRID 설치 시 기본 제공되는 demodb에 접속하여 SELECT 질의를 수행하는 예제이다.
import java.sql.*;
public class SelectData {
public static void main(String[] args) throws Exception {
Connection conn = null;
Statement stmt = null;
ResultSet rs = null;
try {
// CUBRID에 Connect
Class.forName("cubrid.jdbc.driver.CUBRIDDriver");
conn = DriverManager.getConnection("jdbc:cubrid:localhost:30000:demodb:::","dba","");
String sql = "select name, players from event";
stmt = conn.createStatement();
rs = stmt.executeQuery(sql);
while(rs.next()) {
String name = rs.getString("name");
String players = rs.getString("players");
System.out.println("name ==> " + name);
System.out.println("Number of players==> " + players);
System.out.println("\n=========================================\n");
}
rs.close();
stmt.close();
conn.close();
} catch ( SQLException e ) {
System.err.println(e.getMessage());
} catch ( Exception e ) {
System.err.println(e.getMessage());
} finally {
if ( conn != null ) conn.close();
}
}
}
다음은 CUBRID 설치 시 기본 제공되는 demodb에 접속하여 INSERT 질의를 수행하는 예제이다. 데이터 삭제 및 갱신 방법은 데이터 삽입 방법과 동일하므로 아래 코드에서 질의문만 변경하여 사용할 수 있다.
import java.sql.*;
public class insertData {
public static void main(String[] args) throws Exception {
Connection conn = null;
Statement stmt = null;
try {
// CUBRID에 Connect
Class.forName("cubrid.jdbc.driver.CUBRIDDriver");
conn = DriverManager.getConnection("jdbc:cubrid:localhost:30000:demodb:::","dba","");
String sql = "insert into olympic(host_year, host_nation, host_city, opening_date, closing_date) values (2008, 'China', 'Beijing', to_date('08-08-2008','mm-dd-yyyy'), to_date('08-24-2008','mm-dd-yyyy'))";
stmt = conn.createStatement();
stmt.executeUpdate(sql);
System.out.println("데이터가 입력되었습니다.");
stmt.close();
} catch ( SQLException e ) {
System.err.println(e.getMessage());
} catch ( Exception e ) {
System.err.println(e.getMessage());
} finally {
if ( conn != null ) conn.close();
}
}
}