세로형
Recent Posts
Recent Comments
Link
03-29 03:47
«   2024/03   »
1 2
3 4 5 6 7 8 9
10 11 12 13 14 15 16
17 18 19 20 21 22 23
24 25 26 27 28 29 30
31
Archives
Today
Total
관리 메뉴

꿈 많은 사람의 이야기

자바 mysql 접속 및 출력(연동) 본문

java

자바 mysql 접속 및 출력(연동)

이수진의 블로그 2017. 8. 18. 08:43

그리고 기본적인 데이터를 넣어보자
먼저 mysql에서 테이블과 데이터를 넣어보자

create table member( 
code char(4) not null, 
name varchar(30) not null, 
id varchar(30), 
pwd varchar(15), 
age int(3) 
); 


create table saram( 
id varchar(20), 
name varchar(20), 
age tinyint 
); 

insert into member values('1001', '강지아', 'jeea', '1111', 20); 
insert into member values('1002', '이장미', 'rose', '2222', 30); 
insert into member values('1003', '김백합', 'lily', '3333', 25); 

insert into saram(id, name, age) values('HONG', 'Gildong', 23); 
insert into saram(id, name, age) values('LEE', 'Gildong', 23); 
insert into saram(id, name, age) values('KIM', 'Gildong', 23); 
insert into saram(id, name, age) values('KIM', 'Gildong', 43); 

그리고 java에서 다음과 같이 프로그램을 짜본다.


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
 
public class TestJDBC2 {
 
    public static Connection getConnection() throws ClassNotFoundException, SQLException  {
        
        String url = "jdbc:mysql://localhost:3306/test";
        String user = "root";
        String pwd = "yourpasswd";
        Connection conn = null;
        
        Class.forName("org.gjt.mm.mysql.Driver");
        conn = DriverManager.getConnection(url, user, pwd);
        System.out.println("접속");
            
        
        return conn;
    }
    
    public static void main(String[] args) throws ClassNotFoundException, SQLException
    {
        
        Connection conn = getConnection();
        String sql = "SELECT * FROM saram";
        ResultSet rs = null;
        Statement stmt = null;
        
        stmt = conn.createStatement();
        rs = stmt.executeQuery(sql);
        
        while(rs.next())
        {
            String id = rs.getString(1);
            String name = rs.getString(2);
            int age = rs.getInt(3);
            
            System.out.println(id + ", "+name+", "+age);
        }
        
        if(rs != null) rs.close();
        if(stmt != null) stmt.close();
        if(conn != null) conn.close();
    }
 
}
Colored by Color Scripter

 Connection 을 리턴해주는 메소드를 하나 생성한다. 프로그램 실행시 이 메소드가 제대로 실행이되면 계속 지속되고 에러가 나오면 진행되지 않는다.

그리고 sql에 진행할 쿼리를 작성한다. 일단 여기서는 select 문이다.
select문은 ResultSet을 리턴한다. 해당 자료구조로 리턴이 되기 때문에 리턴값을 ResultSet으로 받고 진행한다. 

 stmt = conn.createStatement();
그래서 statement객체를 생성해야 하는데 conncection을 이용해서 Statement를 만드는 createStatement()메소드를 호출한다. 이게 정상적으로 실행되면 

rs = stmt.executeQuery(sql);
실제 쿼리를 진행한다. 그럼 rs에는 ResultSet구조로 데이터가 참조가 되어있다.

while(rs.next())
        {
            String id = rs.getString(1);
            String name = rs.getString(2);
            int age = rs.getInt(3);
            
            System.out.println(id + ", "+name+", "+age);
        }

이제 이 참조된 rs를 이용해 데이터에 접근한다. next()가 존재하면 계속 while을 도는데 돌때마다 rs.getString(1);과 rs.getString(2)를 가지고 온다. 숫자 1,2는 테이블 컬럼 순서인데 rs.getString("name"), rs.getString("id")식으로 컬럼을 직접 서주어 갖고 올 수도 있다.


이 연산이 끝나고 나면 불필요한 연결을 제거하기 위해 close()로 닫아준다. 

참고로 select는 ResultSet으로 받아오지만 insert, update, delete등의 연산은 int로 받아오고 사용하는 메소드도 다르다.

저 셋은 int로 받아오며 성공한 개수 만큼 받아올 수 있다. 즉, 실행된 것이 없으면 1보다 작기 때문에 이 if문으로 조건을 처리할 수 있다.
또한 저 셋은 
stmt.executeQuery(sql);
가 아닌

stmt.executeUpdate(sql); 를 사용해서 진행하면 된다.


반응형
그리드형
Comments