2014-07-06 4 views
0

"원시"데이터가 들어있는 "첫 번째"라는 테이블이있는 "test"라는 데이터베이스가 있는데이 테이블 데이터를 가져 오려고합니다. 테이블에서 "처음"데이터를 가져 오기 위해 사용해야하는 준비 문은 무엇입니까? 아래 코드는 제가 시도하는 코드입니다. 어떤 도움이나 지침도 상당 할 것입니다. MYSQL 데이터베이스에서 데이터를 가져 오는 방법

@Path("/database") // Specific URL 
@GE 
@Produces(MediaType.TEXT_PLAIN) 
public String returnDB_Status() throws Exception { 
    PreparedStatement query = null; 
    String result = null; 
    Connection conn = null; 

    try { 
     conn = mysql_prac.dbConn().getConnection(); // this works fine ... 
     query = conn.prepareStatement("SELECT * from first"); // Table named as "first" is placed inside the connected database. 
     ResultSet rs = query.executeQuery(); 
     result = "Data received : " + rs; 
     query.close(); 

    } catch (Exception e) { 
     e.printStackTrace(); 
    } finally { 
     if (conn != null) 
      conn.close(); 
    } 
    return result; 
} 

사용 된 소스 코드

는 연결

public class mysql_prac { 

    private static DataSource mysql_prac = null; 
    private static Context context = null; 

    public static DataSource dbConn() throws Exception { 
     if (mysql_prac != null) { 
      return mysql_prac; 
     } 

     try { 
      if (context == null) { 
       context = new InitialContext(); 
      } 

      mysql_prac = (DataSource) context.lookup("JDBC_ref"); //JNDI ID (JDBC_REF) 
     } catch (Exception e) { 
      e.printStackTrace(); 

     } 
     return mysql_prac; 
    } 
} 
+0

질문이 명확하지 않습니다. 너는 무엇을 성취하려고 노력하고 있는가? 추가 정보를 입력하십시오. – Namphibian

+0

게시 한 코드가 이미 반환 된 항목은 무엇입니까? 결과가 없습니까? 예외가 있습니까? – tmarwen

+0

@tmarwen ... 그것은 빈 페이지 (출력 없음)를 제공합니다. 연결 후에 어떤 것을 인쇄하면; 이클립스에서 print 문을 보여 주지만 데이터베이스에서 어떤 데이터도 얻지 못한다. – Umair

답변

0

당신은 ResultSet을 통해 루프 각 행의 필드를 얻을 수 있어야합니다을받을. 그래서 나는 다음과 같은 몇 가지 덧글을 함께 편집했다. 의견을주의하십시오.

try { 
     conn = mysql_prac.dbConn().getConnection(); // this works fine ... 
     query = conn.prepareStatement("SELECT * from first"); // Table named as "first" is placed inside the connected database. 
     ResultSet rs = query.executeQuery();//You must loop through the results set to get the fields of each row 

     while(rs.next()){ 
      String dbUserID = rs.getString("column1");//this is just an example to retrieve all data in the column called 'column1' 
      result = "Data received : " + dbUserID; 
      System.out.println(result); 
     } 

     query.close(); 

    } catch (Exception e) { 
     e.printStackTrace(); 
    } finally { 
     if (conn != null) 
      conn.close(); 
    } 
관련 문제