java

쉽지만 어려운 #Java #자바 #성공적 7.Mysql (JDBC) 연동하기 2부

sieunju 2016. 6. 19. 02:09
반응형


안녕하세요 j.sieun 입니다. 


저번 글에 Mysql 설치 및 이클립스와 JDBC(Jaba DataBase Connetivity) 연동하는 법을 배웠습니다. 


이번 시간에 배울 내용은 Mysql 에 Data를 추가하거나 가져오는 것을 배워보도록 하겠습니다. 


먼저, 소스에 대해 알아보겠습니다. 


조건 :  
DB(Database) : test
Table 명 : login_info

Table 추가 명령어 : 
create table test_info(name varchar(30), password int(10), hobby varchar(30));


테이블 속성 


import java.sql.Connection;

import java.sql.DriverManager;

import java.sql.ResultSet;

import java.sql.SQLException;

import java.sql.Statement;

import java.util.Scanner;


public class Jdbc {


public static void main(String[] args) {

// TODO Auto-generated method stub

Scanner sc = new Scanner(System.in);

String index;

while (true) {

System.out.println("1)정보 추가, 2)정보 출력,3)나가기");

index = sc.nextLine();


if (index.equals("1")) {

String name, hobby;

int password;


System.out.println("아이디를 입력하시오");

name = sc.nextLine();

System.out.println("패스워드를 입력하시오");

password = sc.nextInt();

System.out.println("취미를 입력하시오");

hobby = sc.next();

addSql(name, password, hobby);


} else if (index.equals("2")) {

System.out.println("아이디를 적으시오");

String id;

id = sc.next();

showSql(id);


System.out.println("사용자가 가져온 값은");

System.out.println("취미 :" + show_hobby + "\n암호 :"

+ show_password);

} else if (index.equals("3")) {

System.out.println("종료합니다. ");

System.exit(0);

}

}

}


// 데이터 추가

static void addSql(String name, int password, String hobby) {


try {

Class.forName("com.mysql.jdbc.Driver");


} catch (ClassNotFoundException e) {

System.out.println("소스 에러가 떳습니다.");

}

try {


Connection con = DriverManager.getConnection(

"jdbc:mysql://localhost/test", "root", "");

Statement st = con.createStatement();


String addData = "insert into login_info (name,password,hobby)"

+ "values('" + toLatin1(name) + "',+'" + password + "','"

+ toLatin1(hobby) + "');";


st.executeUpdate(addData);

} catch (SQLException e) {

System.out.println("SQLException :" + e.getMessage());

}

}


// 추가한 데이터 보여주기

static int show_password;

static String show_hobby;


static void showSql(String str) {

try {

Class.forName("com.mysql.jdbc.Driver");


} catch (ClassNotFoundException e) {

System.out.println("소스 에러가 떴습니다.");

}

try {


Connection con = DriverManager.getConnection(

"jdbc:mysql://localhost/test", "root", "");


Statement stmt = con.createStatement();


ResultSet rs = stmt.executeQuery("select * from  login_info where name='"

+ toLatin1(str) + "';");

while (rs.next()) {

int password1 = rs.getInt("password");

String hobby = rs.getString("hobby");

hobby = toUnicode(hobby);

show_password = password1;

show_hobby = hobby;

}


stmt.close();

con.close();

} catch (SQLException e) {

System.out.println("SQLException :" + e.getMessage());

}

}


// 데이터 보내거나 가져올 때 인코딩 해주는 메소드

static String toLatin1(String str) {

try {

byte[] b = str.getBytes();

return new String(b, "ISO-8859-1");


} catch (java.io.UnsupportedEncodingException uee) {

System.out.println(uee.getMessage());

return null;

}

}


static String toUnicode(String str) {

try {

byte[] b = str.getBytes("ISO-8859-1");

return new String(b);

} catch (java.io.UnsupportedEncodingException uee) {

System.out.println(uee.getMessage());

return null;

}

}


}

출력 결과


소스 부분 해석:

Statement st = con.createStatement();

:DB(DataBase) 조회 하는 부분

st.executeUpdate(addData);
: Data를 업데이트 해주는 부분

ResultSet rs = stmt.executeQuery("select * from  login_info where name='"+ toLatin1(str) + "';");

:Data 를 조회 하는 부분

while (rs.next()) {};

:가져온 Data를 읽어오는 부분






DB같은 경우는 거의 대부분 자바 GUI(Graphic User Interface)를 이용해서 사용하는 경우가 대부분 이지만, 저는 쉽게 이해할 수 있도록 "Scanner Method"를 이용하여  간단하게 표현했습니다. 

위에 소스 중에서 중요하게 봐야 할 점이 몇 개 있습니다. 

제가 생각하기에 가장 실수를 많이 하는 부분 

첫번째는

Connection con = DriverManager.getConnection("jdbc:mysql://localhost/test", "root", "");

입니다. DB(DataBase) 연결 하는 부분입니다. 

정의로 표현하자면 

Connection con = DriverManager.getConnection("Mysql연결 경로\DB명","사용자 계정","비밀번호");

이 되겠습니다. 


두번째는

"select * from  login_info where name='"+ toLatin1(str) + "';" 

이 되겠습니다. 

' 작은 따옴표와 " 큰따옴표를 적절히 잘 섞어야 하기 때문에 실수가 많습니다. 


참고하셔야할 메소드는


toLatin1(String str)  toUnicode(String str) 이 되겠습니다. 


toLatin1 의 경우 한글 or 영어를 Mysql 에 추가할 때 쓰이는 부분 이고,

toUnicode 의 경우 한글 or 영어를 이클립스에서 출력 할 때 쓰이는 부분입니다.



※궁금하신거 댓글달아주시길 바랍니다. ㅎㅎ


퍼가시는건 상관 없는데 말은 하고 퍼가주시길 바랍니다.^^※










반응형