반응형
Java_PreparedStatement
PreparedStatement 개념 및 예제
출처
https://sas-study.tistory.com/160
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Scanner;
class DBConn{
private static DBConn db;
public static DBConn getInstance() {
if(db==null) {
db = new DBConn();
}
return db;
}
public Connection getconn() {
Connection con = null;
try {
Class.forName("org.mariadb.jdbc.Driver");
String url = "jdbc:mariadb://220.70.33.29:3306/unknown";
con = DriverManager.getConnection(url, "unknown", "01234567");
} catch (Exception e) {
e.printStackTrace();
System.out.println("sql 접속오류");
}
return con;
}
}
public class Login {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
Connection conn = DBConn.getInstance().getconn();
System.out.println("아이디를 입력하세요.");
String id = sc.next();
System.out.println("비밀번호를 입력하세요.");
String pw = sc.next();
String sql = "SELECT * FROM login WHERE id=? AND pw=?";
//PreparedStatement
PreparedStatement pstmt = null;
try {
pstmt = conn.prepareStatement(sql);
//실제 sql에 데이터 붙이기
pstmt.setString(1, id); //물음표 위치에 어떤 값
pstmt.setString(2, pw); //적어주기 (위치, 값)
// 실행
ResultSet rs = pstmt.executeQuery();
if(rs != null) {
if(rs.next()) {
System.out.println(rs.getString("name"));
}
}
} catch (SQLException e) {
e.printStackTrace();
}
}
}
반응형
'프로그래밍 > Java 공부' 카테고리의 다른 글
JAVA - Thread(스레드) (0) | 2021.06.30 |
---|---|
Java_DTO (0) | 2021.06.23 |
자바_POI활용, JXL활용 엑셀 문서로 저장하기 (0) | 2021.06.23 |
Java_IO(파일 입출력) (0) | 2021.06.22 |
Java_Inner Class 내부 클래스 (0) | 2021.06.22 |