위 글은 김성박선생님의 자바 강의를 바탕으로 쓰여졌습니다.
더 자세한 내용은 아래 링크를 통해 알아보실 수 있습니다.
Scanner를 통해 데이터를 입력받도록 하자.
package com.example.jdbcprj;
import java.sql.*;
import java.util.Scanner;
public class Program2 {
public static void main(String[] args) throws SQLException {
Scanner sc = new Scanner(System.in);
String title = sc.nextLine();
String writer_id = sc.nextLine();
String content = sc.nextLine();
Connection conn = DriverManager.getConnection("jdbc:mysql://127.0.0.1:3306/testdb?useSSL=false&serverTimezone=Asia/Seoul&useUnicode=true&character_set_server=utf8mb4", "root","gkseogh1!23");
String sql = "INSERT INTO notice(title, writer_id, content) VALUES (?,?,?)";
// PreparedStatement
PreparedStatement ps = conn.prepareStatement(sql);
ps.setString(1, title);
ps.setString(2,writer_id);
ps.setString(3,content);
int result = ps.executeUpdate();
System.out.println(result);
ps.close();
conn.close();
}
}
위와 같은 쿼리문을 수정해 보도록 하자.
package com.example.jdbcprj;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.Scanner;
public class Program3 {
public static void main(String[] args) throws SQLException {
Scanner sc = new Scanner(System.in);
System.out.println("Please input id");
int id = Integer.parseInt(sc.nextLine());
System.out.println("WRITE!! title, writer_id, content HERE!!!. ex) enter ");
String title = sc.nextLine();
String writer_id = sc.nextLine();
String content = sc.nextLine();
Connection conn = DriverManager.getConnection("jdbc:mysql://127.0.0.1:3306/testdb?useSSL=false&serverTimezone=Asia/Seoul&useUnicode=true&character_set_server=utf8mb4", "root","gkseogh1!23");
String sql = "UPDATE NOTICE SET title =?, content = ? , writer_id = ? where id = ?";
// PreparedStatement
PreparedStatement ps = conn.prepareStatement(sql);
ps.setString(1, title);
ps.setString(2,content);
ps.setString(3,writer_id);
ps.setInt(4, id);
int result = ps.executeUpdate();
System.out.println(result);
ps.close();
conn.close();
}
}
package com.example.jdbcprj;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.Scanner;
public class Program4 {
public static void main(String[] args) throws SQLException {
Scanner sc = new Scanner(System.in);
System.out.println("Please delete for id");
int id = Integer.parseInt(sc.nextLine());
Connection conn = DriverManager.getConnection("jdbc:mysql://127.0.0.1:3306/testdb?useSSL=false&serverTimezone=Asia/Seoul&useUnicode=true&character_set_server=utf8mb4", "root","gkseogh1!23");
String sql = "DELETE FROM notice WHERE ID = ?";
// PreparedStatement
PreparedStatement ps = conn.prepareStatement(sql);
ps.setInt(1, id);
int result = ps.executeUpdate();
System.out.println(result);
ps.close();
conn.close();
}
}