Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- package dbConnect;
- import java.sql.Connection;
- import java.sql.DriverManager;
- import java.sql.PreparedStatement;
- import java.sql.ResultSet;
- import java.sql.Statement;
- public class dbConnect {
- private Connection conn;
- private Statement stmt;
- private PreparedStatement pstmt;
- private ResultSet rs;
- /* 세팅 입력값 */
- private static final String dbDriver = "org.mariadb.jdbc.Driver";
- private static final String dbtConnectionURL = "jdbc:mysql://localhost:3306/dbName";
- private static final String dbUserId = "";
- private static final String dbUserPassword = "";
- public void dbDisconn() {
- try {
- if(rs != null) rs.close();
- System.out.println("rs close 완료");
- if(stmt != null) stmt.close();
- System.out.println("stmt close 완료");
- if(conn != null) conn.close();
- System.out.println("conn close 완료");
- } catch (Exception e2) {
- // TODO: handle exception
- }
- }
- public void insertDBSong(String artist, String title) {
- try {
- // 3. 열기
- stmt = conn.createStatement();
- String insert = "";
- insert = "INSERT INTO chart";
- insert += " VALUES ('1',\' " + title + " \', \'"+ artist +" \')";
- pstmt = conn.prepareStatement(insert);
- pstmt.execute(insert);
- boolean flag = stmt.execute(insert);
- if (flag) {
- System.out.println("입력완료");
- }
- } catch (Exception e) {
- System.out.println("처리 오류 : " + e);
- }
- }
- public void getDBSong() {
- try {
- // 3. 열기
- stmt = conn.createStatement();
- // 4. 자료 읽기
- /**자료 한개 읽어오기**/
- rs = stmt.executeQuery("select * from chart");
- // sql문장을 실행하고 re에 저장
- rs.next();
- // Record pointer 이동 : Rec Pointer가 있는 지점 자료만 참조 가능 레코드는 한줄씩(row)만 읽어올수 있음
- // Record pointer의 처음 위치는 0번째이기 때문에 next() 로 1번째 레코드로 이동해야 첫번째 자료를 읽어올수있음
- String title = rs.getString("title");
- String artist = rs.getString("artist");
- // 읽어온 row에서 각 컬럼명으로 값을 찾아서 변수에 저장
- System.out.println("자료 한줄 읽어오기");
- System.out.println(title + " " + artist + " " );
- /**자료 여러개 읽어오기**/
- System.out.println("\n 자료 여러개 읽어오기");
- String sql = "select title as 노래제목, artist as 가수, num from chart";
- // rs = stmt.executeQuery(sql);
- /*
- while(rs.next()) {
- // rs.next()는 re.next() == true 와 같은 뜻
- // rs.next()가 존재할때까지 즉, 한줄 한줄 읽어오면서 자료가 존재하면 계속 반복
- String code2 = rs.getString("코드");
- // 칼럼에 별명을 설정해주면 불러올때 별명을 써야한다 안그럴시 부적합한 열 이름오류
- String sang2 = rs.getString(2);
- // 읽어온 컬럼 순서에 맞춰서 컬럼명 대신 순서를 넣어도 읽어올수있다.
- int su2 = rs.getInt("su");
- // sangdata 테이블의 dan의 데이터형은 int 이지만 계산이 필요하지 않을때는 그냥 String로 불러와도 된다.
- // 즉, DB의 변수형과 java의 변수형을 일치하지 않아도 된다.
- String dan2 = rs.getString("dan");
- System.out.println(code2 + " " + sang2 + " " + su2 + " " + dan2);
- }
- */
- /**전체 자료 수 출력**/
- System.out.println("\n 전체 자료수 출력");
- sql = "select count(*) from chart";
- rs = stmt.executeQuery(sql);
- rs.next();
- System.out.println("건수 : " + rs.getInt(1));
- String insert = "INSERT INTO chart VALUES ('3','I Believe', '신승훈')";
- stmt.execute(insert);
- } catch (Exception e) {
- System.out.println("처리 오류 : " + e);
- }
- }
- public dbConnect() {
- // 1. Driver 로딩
- try {
- Class.forName(dbDriver);
- } catch (Exception e) {
- System.out.println("로딩 실패");
- return;
- }
- // 2. DB와 연결 (cmd에서 '-mysql -u root -p ' 한것과 같다)
- try {
- conn = DriverManager.getConnection(dbtConnectionURL, dbUserId, dbUserPassword);
- System.out.println("연결성공!");
- //conn = DriverManager.getConnection("jdbc:mysql://ip주소:포트번호/db명", "id", "pw");
- //mariadb는 mysql에서 나왔기때문에 같은 드라이버를 쓴다.
- } catch (Exception e) {
- System.out.println("연결 실패 : " + e);
- }
- try {
- // 3. 열기
- stmt = conn.createStatement();
- // 4. 자료 읽기
- //**자료 한개 읽어오기**//
- rs = stmt.executeQuery("select * from chart");
- // sql문장을 실행하고 re에 저장
- rs.next();
- // Record pointer 이동 : Rec Pointer가 있는 지점 자료만 참조 가능 레코드는 한줄씩(row)만 읽어올수 있음
- // Record pointer의 처음 위치는 0번째이기 때문에 next() 로 1번째 레코드로 이동해야 첫번째 자료를 읽어올수있음
- String title = rs.getString("title");
- String artist = rs.getString("artist");
- // 읽어온 row에서 각 컬럼명으로 값을 찾아서 변수에 저장
- System.out.println("자료 한줄 읽어오기");
- System.out.println(title + " " + artist + " " );
- //**자료 여러개 읽어오기**//*
- System.out.println("\n 자료 여러개 읽어오기");
- String sql = "select title as 노래제목, artist as 가수, num from chart";
- // rs = stmt.executeQuery(sql);
- while(rs.next()) {
- // rs.next()는 re.next() == true 와 같은 뜻
- // rs.next()가 존재할때까지 즉, 한줄 한줄 읽어오면서 자료가 존재하면 계속 반복
- String code2 = rs.getString("코드");
- // 칼럼에 별명을 설정해주면 불러올때 별명을 써야한다 안그럴시 부적합한 열 이름오류
- String sang2 = rs.getString(2);
- // 읽어온 컬럼 순서에 맞춰서 컬럼명 대신 순서를 넣어도 읽어올수있다.
- int su2 = rs.getInt("su");
- // sangdata 테이블의 dan의 데이터형은 int 이지만 계산이 필요하지 않을때는 그냥 String로 불러와도 된다.
- // 즉, DB의 변수형과 java의 변수형을 일치하지 않아도 된다.
- String dan2 = rs.getString("dan");
- System.out.println(code2 + " " + sang2 + " " + su2 + " " + dan2);
- }
- //**전체 자료 수 출력**//
- System.out.println("\n 전체 자료수 출력");
- sql = "select count(*) from chart";
- rs = stmt.executeQuery(sql);
- rs.next();
- System.out.println("건수 : " + rs.getInt(1));
- String insert = "INSERT INTO chart VALUES ('3','I Believe', '신승훈')";
- stmt.execute(insert);
- } catch (Exception e) {
- System.out.println("처리 오류 : " + e);
- } finally {
- // 5. 연결 끊기 - 작업이 끝나면 닫아주어야 한다
- try {
- if(rs != null) rs.close();
- if(stmt != null) stmt.close();
- if(conn != null) conn.close();
- } catch (Exception e2) {
- // TODO: handle exception
- }
- }
- }
- public static void main(String[] args) {
- new dbConnect();
- }
- }
Add Comment
Please, Sign In to add comment