반응형
Notice
Recent Posts
Recent Comments
Link
«   2024/05   »
1 2 3 4
5 6 7 8 9 10 11
12 13 14 15 16 17 18
19 20 21 22 23 24 25
26 27 28 29 30 31
Tags
more
Archives
Today
Total
관리 메뉴

디케이

MySQL 에서 데이터 받아오기_첫 연습 본문

SQL

MySQL 에서 데이터 받아오기_첫 연습

디케이형 2020. 11. 12. 02:45
반응형

MySQL 코딩

DROP DATABASE IF EXISTS a1;
CREATE DATABASE a1;
USE a1;
CREATE TABLE article (
id INT(10) UNSIGNED PRIMARY KEY NOT NULL AUTO_INCREMENT,
`date` DATETIME NOT NULL,
writer CHAR(100) NOT NULL,
title VARCHAR(100) NOT NULL,
hit INT(10) NOT NULL
);
DESC article;

SELECT * FROM article;

INSERT article 
SET id=1,
`date`='2020-11-11 12:12:12',
writer='임꺽정',
title='안녕하세요1',
hit=21;

INSERT article 
SET `date`='2020-11-11 12:12:12',
writer='홍길동',
title='안녕하세요2',
hit=33;

INSERT article 
SET `date`='2020-11-11 12:12:12',
writer='홍길순',
title='안녕하세요3',
hit=55;
/* 실행 안될때 .. 
SELECT @@global.time_zone, @@session.time_zone;
set global time_zone='+09:00';
SET time_zone='+09:00';
*/

JSP에 코팅

package example;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
import java.sql.Timestamp;
import java.util.Scanner;

public class Main {
	public static void main(String[] args) {
		Scanner sc = new Scanner(System.in);
		System.out.printf("명령어) ");
		String cmd = sc.nextLine();
		try {
			// 데이터베이스 Connection
			Class.forName("com.mysql.cj.jdbc.Driver");
			Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/a1?severTimezone=UTC", "sbsst", "sbs123414");
			// select 쿼리
			// 테이블 불러오기
			String qu = "select * from article order by id desc";
			// java statement 생성
			Statement st = con.createStatement();
			// 쿼리 execute , 객체형성
			ResultSet rs = st.executeQuery(qu);
			// article list 입력을 받으면 실행
			if (cmd.equals("article list")) {
				System.out.println("== 게시물 리스트 ==");
				System.out.println("번호 / 날짜 / 작성자 / 제목 / 조회수");
				// 각 열을 반복적으로 나타내줌
				while (rs.next()) {
					int id = rs.getInt("id");
					Timestamp date = rs.getTimestamp("date"); // 자바로 넘어 오면서 String으로 변환
					String writer = rs.getString("writer");
					String title = rs.getString("title");
					int hit = rs.getInt("hit");

					// 결과값 도출 (%s당 id 같은 정보를 출력해줌)
					System.out.format("%d / %s / %s / %s / %d\n", id, date, writer, title, hit);
				}
				// 닫아줌
				st.close();
			}

			// 캐치
		} catch (Exception e) {
			System.err.println("Got an exception! ");
			System.err.println(e.getMessage());

		}
	}
}

 

반응형