π νμ©
package pack5db;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.Scanner;
public class DbTest5 {
public DbTest5() {
dbLoading();
insertDb();
selectDb();
}
private Connection conn;
private PreparedStatement pstmt;
private ResultSet rs;
private void dbLoading() {
try {
Class.forName("org.mariadb.jdbc.Driver");
} catch (Exception e) {
System.out.println("λ‘λ© μ€ν¨ :" +e);
System.exit(0);
}
}
private void insertDb() {
try {
Scanner scanner = new Scanner(System.in);
conn = DriverManager.getConnection("jdbc:mariadb://127.0.0.1:3306/test","root","λΉλ°λ²νΈ");
while(true) {
System.out.print("code : ");
String code = scanner.next();
System.out.print("sang : ");
String sang = scanner.next();
System.out.print("su : ");
String su = scanner.next();
System.out.print("dan : ");
String dan = scanner.next();
pstmt = conn.prepareStatement("insert into sangdata values(?,?,?,?)");
pstmt.setString(1, code);
pstmt.setString(2, sang);
pstmt.setString(3, su);
pstmt.setString(4, dan);
pstmt.executeUpdate();
System.out.print("κ³μν κΉμ (y/n) :");
String yn = scanner.next();
if(yn.equalsIgnoreCase("n")) break;
}
scanner.close();
} catch (Exception e) {
System.out.println("insertDb err : " +e );
}finally {
try {
if (rs != null) rs.close();
if (pstmt != null) pstmt.close();
if (conn != null) conn.close();
} catch (Exception e2) {
}
}
}
private void selectDb() {
try {
conn = DriverManager.getConnection("jdbc:mariadb://127.0.0.1:3306/test","root","λΉλ°λ²νΈ");
String sql = "select * from sangdata";
pstmt = conn.prepareStatement(sql);
rs = pstmt.executeQuery();
int count = 0;
System.out.println("μ½λ\tμνλͺ
\tμλ\tλ¨κ°");
while(rs.next()) {
System.out.println(rs.getString(1) + "\t" +
rs.getString(2) + "\t" +
rs.getString(3) + "\t" +
rs.getString(4));
count += 1;
}
System.out.println("건 μ :" +count + "κ°");
} catch (Exception e) {
System.out.println("selectDb err : " +e );
}finally {
try {
if (rs != null) rs.close();
if (pstmt != null) pstmt.close();
if (conn != null) conn.close();
} catch (Exception e2) {
}
}
}
public static void main(String[] args) {
new DbTest5();
}
}
π μΆλ ₯