DB 7일차(java, sql 연결 select)
2022. 12. 15. 09:51ㆍ코딩배움일지/DataBase
어제
import java.sql.Connection;
import main.java.com.study.jdbc.util.DBConnection;
public class jdbcTest1 {
public static void main(String[] args) {
Connection connection = DBConnection.getInstance().getConnection();
System.out.println(connection);
}
}
오늘
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import main.java.com.study.jdbc.util.DBConnection;
public class jdbcTest1 {
public static void main(String[] args) {
Connection connection = DBConnection.getInstance().getConnection();
String sql = "select * from score_mst ";
try {
PreparedStatement pstmt = connection.prepareStatement(sql);
ResultSet rs = pstmt.executeQuery(); /*해석한다*/
System.out.println("id:\tname\t\tscore");
while(rs.next()) {
System.out.println("id: " + rs.getInt(1)
+ "\t name: " + rs.getString(2)
+ "\t score: " + rs.getInt(3));
}
} catch (SQLException e) {
e.printStackTrace();
}
}
}
결과
데이터베이스 드라이브 로딩 성공!
id: name score
id: 1 name: 신경수 score: 100
id: 2 name: 고희주 score: 95
id: 3 name: 장건녕 score: 85
id: 4 name: 문승주 score: 80
id: 5 name: 이승아 score: 75
id: 6 name: 김수현 score: 65
id: 7 name: 문경원 score: 50
서로간의 연결이 필요하다.
connection = DriverManager.getConnection(url, username, password);
getConnection 을 가지고 connection 객체를 만들었다. 정보는 (url, username, password)
Connection connection = DBConnection.getInstance().getConnection();
Singleton 을 가지고 getConnection 메소드를 들고 온다.
PreparedStatement pstmt = connection.prepareStatement(sql); /*연결된 커넥션 객체에 sql을 prepareStatement(sql) 연결해달라.*/
연결된 커넥션 객체에 sql을 prepareStatement(sql) 연결해달라. 반환자료형 pstmt
ResultSet rs = pstmt.executeQuery(); /*해석한다.*/ /* executeQuery() 호출 되면 쿼리를 실행한다.*/
while(rs.next()) { /*false 가 뜰때가지 반복한다.*/ /*next 있으면 true */
System.out.println("id: " + rs.getInt(1) /*컬럼번호(1) 부터 시작한다.*/
+ "\t name: " + rs.getString(2)
+ "\t score: " + rs.getInt(3));
}
'코딩배움일지 > DataBase' 카테고리의 다른 글
DB 7일차 2-1(조건을 주고싶을때) (0) | 2022.12.15 |
---|---|
DB 7일차 2() (0) | 2022.12.15 |
DB 6일차 4(jdbc) (0) | 2022.12.14 |
DB 6일차 3-1(union) (0) | 2022.12.14 |
DB 6일차 3(조건) (0) | 2022.12.14 |