프로그래밍/Java
Java 9일차 - MySQL연동
비전공개미
2022. 9. 28. 17:46
반응형
SMALL
MySQL DB연동 / INSERT, SELECT
//DB.java
package net.bit.day28;
import java.sql.Connection;
import java.sql.DriverManager; //Connection CN = DriverManager.getConnection()
public class DB {
public static Connection getConnection() {
Connection CN = null;
try {
Class.forName("com.mysql.cj.jdbc.Driver");
String url = "jdbc:mysql://localhost:3306/naver";
CN = DriverManager.getConnection(url, "root", "1234");
System.out.println("DB.java문서 mysql데이터 연결 성공");
}catch(Exception e) { }
return CN;
}
}
//DBTest.java
package net.bit.day28;
import java.util.Scanner;
import java.sql.Connection; //Connection CN은 db서버ip정보, 계정id, 비밀번호
import java.sql.DriverManager; //Connection CN = DriverManager.getConnection()
import java.sql.Statement; //ST = CN.createStatement()
import java.sql.PreparedStatement; //PST = CN.prepareStatement("INSERT INTO / UPDATE");
import java.sql.ResultSet; //RS = ST.executeQuery("SELECT ~ FROM");
public class DBTest {
Scanner sc = new Scanner(System.in);
String msg = ""; //insert ~~, select ~~, update where ~~, delete where ~~
Connection CN;
Statement ST;
PreparedStatement PST;
ResultSet RS;
public DBTest() {
try {
DB.getConnection();
}catch(Exception e) { System.out.println("에러이유 : " + e); }
}
public void dbInsert() {
System.out.println("신규데이터 입력");
try {
System.out.println("저자입력 >>> "); String a = sc.nextLine();
System.out.println("제목입력 >>> "); String b = sc.nextLine();
System.out.println("메모입력 >>> "); String c = sc.nextLine();
//msg = "insert into bit(author, title, memo) values ('a', 'b', 'c')";
msg = "insert into bit(author, title, memo) values ('"+a+"', '"+b+"', '"+c+"')";
ST = CN.createStatement(); //명령어생성
int OK = ST.executeUpdate(msg); //명령어실행
System.out.println(a + "데이터 저장 성공했습니다");
}catch(Exception e) { System.out.println("에러이유 : " + e); }
}
public void dbSelectAll() {
System.out.println("전체데이터 출력");
System.out.println("저자\t 제목\t 메모");
try {
msg = "select * from bit"; //단순한 문자열
ST = CN.createStatement(); //명령어생성
//실행할때 executeQuery() <= select는 명령어가 다름
RS = ST.executeQuery(msg); //단순한 문자열msg 변수 쿼리문 적용
while(RS.next()) {
String a = RS.getString("author");
String b = RS.getString("title");
String c = RS.getString("memo");
System.out.println(a + "\t" + b + "\t" + c);
}
}catch(Exception e) { System.out.println("전체조회 에러이유 : " + e); }
}
public int dbCount() { return 0; }
public void dbDelete() { }
public void dbUpdate() { }
public void dbDetail() {
//저자데이터로 한건
}
public static void main(String[] args) {
DBTest ob = new DBTest(); //db연결
ob.dbSelectAll();
System.out.println("-------------------------------------------");
//조회가 성공이면 신규등록처리
ob.dbInsert();
try { Thread.sleep(500); }catch(Exception e) { }
}
}
반응형
LIST