본문 바로가기
  • fishing...
  • eating...
MISCELLANEOUSNESS

[JDBC ]MySQL 데어터 불러오기

by 회색뿔 2007. 12. 12.


[JDBC] MySQL SQL문 실행 및 결과 값 얻기.

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

public class ConnectionDB
{
     Connection conn = null;
 
     String host = "localhost", database ="test";
     int port = 3306;
 
     public ConnectionDB()
     {
          try
          {
               Class.forName("com.mysql.jdbc.Driver");

               //Class.forName( "com.mysql.jdbc.Driver" );
               conn = DriverManager.getConnection( "jdbc:mysql://" + host + ":"
                                   + port +"/"  + database, "root", "1111" );
               System.out.println( " Successed!!");
   
               Statement stmt = conn.createStatement();
               ResultSet rs = stmt.executeQuery( "select * from test" );
   
               while( rs.next() )
               {
                    int num = rs.getInt( 1 );
   
                    System.out.println( num );
               }
          } catch( SQLException e)
          {
               e.printStackTrace();
          } catch(Exception e)
          {
               e.printStackTrace();
          }
     }
 
     public static void main( String[] args )
     {
          ConnectionDB DB = new ConnectionDB();
     }
}



Statement 쿼리를 하거나 작업 명령을 전달하는데 사용

Statement stmt = conn.createStatement();

ResultSet객체의 get*()메소드를 이용해서 SQL 실형 결과를 얻을 수 있다.

 ResultSet rs = stmt.executeQuery( "select * from test" );

rs.next() : 다음 레코드로 이동
rs.getInt( 1 ) : 실행 결과에서 1번째 데이터를 반환

while( rs.next() )
{
     int num = rs.getInt( 1 );
     System.out.println( num );
}


'MISCELLANEOUSNESS' 카테고리의 다른 글

미래사회 10대 트렌드  (0) 2008.01.07
MySQL데이터 타입  (4) 2007.12.12
어셈 블리어..  (0) 2007.12.11