JAVA(4)-JDBC(DB연결)

Wooney98·2022년 11월 8일
1

JAVA

목록 보기
4/8
post-thumbnail

설치 방법

명령어

create database comstudy21; ## DB 생성
drop database comstudy21; ## DB 삭제
show databases; ## DB 목록 확인

## comstudy DB 선택
use comstudy21; 

##사용자 생성 계정
create user 'comstudy21'@'localhost' identified by 'comstudy21';

##사용자에게 DB권한 부여
grant all privileges on comstudy21.* to 'comstudy21'@'localhost';

##적용
flush privileges;

## 테이블 생성
create table saram(
id varchar(20),
name varchar(20),
age int
);

## 테이블 삭제
drop table saram


## 내용넣기
insert into saram (id,name,age) values ('hong','gildong',25);
## 적용
commit;
## 내용확인
select * from saram;
## 수정하기
update saram set age=29 where id='lee';
## 삭제하기
delete from saram where id='lee';
## 검색하기
select *from saram where id='lee';

드라이버 검색

  • mvnrepository -> mariadb 검색
    - https://mvnrepository.com/artifact/org.mariadb.jdbc/mariadb-java-client
  • 2.7.3 jar 다운로드
  • 프로젝트의 workspace로 옮긴다.
  • 해당 프로젝트 우클릭
    - build path -> config build path -> Libraries -> Classpath -> add External JAR
    • jar 파일에서 -> org.mariadb.jdbc -> Driver.class 우클릭 -> copy name 후 코드에 try~catch로 코드 작성하기.
public class TestJDBC {
	public static void main(String[] args) {
		try {
			Class.forName("org.mariadb.jdbc.Driver.class");
			System.out.println("드라이버 클래스 검색 성공!");
		} catch (ClassNotFoundException e) {
			// TODO Auto-generated catch block
			System.out.println("드라이버 클래스 검색 실패!");
			e.printStackTrace();
		}
	}
}

DB 연결

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

public class TestJDBC {
	public static void main(String[] args) {
		try {
			// 드라이버 클래스를 찾기!
			// 클래스는 .class 확장자를 쓰지않는다.
			Class.forName("org.mariadb.jdbc.Driver");
			System.out.println("드라이버 클래스 검색 성공!");
// localhost : 프로토콜 - ip - port번호 - DB
// ex) jdbc:mariadb://ip주소:port번호/DB이름
			String url = "jdbc:mariadb://localhost/comstudy21";
			String user = "comstudy21";
			String password = "comstudy21";
			Connection conn = DriverManager.getConnection(url, user, password);
			System.out.println(conn);
		} catch (ClassNotFoundException e) {
			// TODO Auto-generated catch block
			System.out.println("드라이버 클래스 검색 실패!");
			e.printStackTrace();
		} catch (SQLException e) {
			System.out.println("DB 접속 실패!");
			e.printStackTrace();
		}
	}
}

Connection & close

public class jdbcUtil {
	private static String url = "jdbc:mariadb://127.0.0.1:3306/comstudy21";
	private static String user = "comstudy21";
	private static String password = "comstudy21";
	
	public static Connection getConnection() {
		try {
			Class.forName("org.mariadb.jdbc.Driver"); //JDB 드라이브 로드
			Connection conn = DriverManager.getConnection(url, user, password);
			return conn; // DB 연결 객체인 Connection 생성
		} catch (ClassNotFoundException e) {
			System.out.println("드라이버 클래스 검색 실패!");
			e.printStackTrace();
		} catch (SQLException e) {
			System.out.println("DB 접속 실패!");
			e.printStackTrace();
		}
		return null;
	}
	
	public static void close(Connection conn) {
		if(conn!=null) {
			try {
				conn.close();
			} catch (SQLException e) {
				e.printStackTrace();
			}
		}
	}
}
	
profile
👨Education Computer Engineering 🎓Expected Graduation: February 2023 📞Contact info thstjddn77@gmail.com

0개의 댓글