티스토리 뷰

JDBC를 사용하여 JAVA와 Database를 연동하는 기초적인 예제를 지난 포스팅에서 다뤘으니, 이번에는 조금 난이도를 올려서 해당 개념을 그대로 활용하는 문제를 풀었다. 

 

문제와 활용할 데이터는 다음과 같다.

 

 1) 주어진 파일을 이용하여 데이터베이스에 저장한 후, 저장된 데이터를 HTML파일로 생성하여 테이블을 표현

 2) 셀프, 비셀프 주유소의 개수를 각각 파악하여 콘솔창에 출력

 

◎oil.xls:


계속 풀어왔던 유형에 DB를 살짝 가미한 정도의 문제이다. 엑셀 파일을 그대로 읽어와 객체로 저장한 뒤, 이를 DB에 삽입하여 HTML형식으로 출력하면 된다. (살짝 돌아가는 느낌이지만, 배운다는 마음으로 돌아가보자)

 


○OilInfo.java: Excel 파일에서 읽어들인 정보를 객체화하기 위한 클래스

package com.choonham.data;

public class OilInfo {

	private String name;
	private String address;
	private String brand;
	private String phone;
	private int isSelf;
	private int gasoline;
	private int diesel;

	public OilInfo() {
		// TODO Auto-generated constructor stub
	}

	public OilInfo(String name, String address, String brand, String phone, String isSelf, String gasoline,
			String diesel) {
		this.name = name;
		this.address = address;
		this.brand = brand;
		this.phone = phone;

		if (isSelf.equals("Y"))
			this.isSelf = 1;
		else
			this.isSelf = 0;

		this.gasoline = Integer.parseInt(gasoline);
		this.diesel = Integer.parseInt(diesel);
	}

	public String getName() {
		return name;
	}

	public String getAddress() {
		return address;
	}

	public String getBrand() {
		return brand;
	}

	public String getPhone() {
		return phone;
	}

	public int isSelf() {
		return isSelf;
	}

	public int getGasoline() {
		return gasoline;
	}

	public int getDiesel() {
		return diesel;
	}

}

○DataClass.java: OilInfo 배열을 static으로 가지고 있고, Data를 체크하는 메서드를 가지고 있는 클래스

package com.choonham.data;

import java.util.ArrayList;

public class DataClass {

	public static ArrayList<OilInfo> oilInfoArray = new ArrayList<>();
	
	public DataClass() {
		
	}
	
	public static void checkData() {
		for(int i = 0; i < oilInfoArray.size(); i++) {
			System.out.println(oilInfoArray.get(i).getName() + " | " + oilInfoArray.get(i).getBrand() + " | " +
					oilInfoArray.get(i).getPhone() + " | "  + oilInfoArray.get(i).getAddress() + " | " + oilInfoArray.get(i).isSelf() + " | "
					+oilInfoArray.get(i).getDiesel() + " | " + oilInfoArray.get(i).getGasoline());
		}
	}

}

○Methods.java: 활용할 메서드를 선언해놓은 인터페이스

package com.choonham.util;

public interface Methods {
	/* 엑셀 파일 Read 하는 메서드 */
	public void readExcel(String uri);

	/* DB에 Read한 데이터 저장하는 메서드 */
	public int setDataInto();

	/* DB에서 데이터 추출 후, HTML Tags 생성하는 메서드 */
	public String makeTags();

	/* Tags를 사용하여 HTML 파일 생성하는 메서드 */
	public void makeHTML(String tags, String uri);

}

 


○MethodsClass.java: 활용할 메서드를 각각 정의한 클래스(내용이 많아, 메서드별로 끊었다.)

 

 1) readExcel(String uri): 엑셀 파일을 읽어 객체화

@Override
	public void readExcel(String uri) {
		File file = new File(uri);
		Workbook wb = null;
		ArrayList<String> tempArray = new ArrayList<>();
		try {
			wb = Workbook.getWorkbook(file);
			Sheet sheet = wb.getSheet(0);
			Cell cell = null;
			int n = 4;
			while (true) {
				try {
					for (int i = 0; i < 7; i++) {
						cell = sheet.getCell(i, n);
						tempArray.add(cell.getContents());
					}
					DataClass.oilInfoArray.add(new OilInfo(tempArray.get(0), tempArray.get(1), tempArray.get(2),
							tempArray.get(3), tempArray.get(4), tempArray.get(5), tempArray.get(6)));
					tempArray.clear();
					n++;
				} catch (Exception e) {
					break;
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

 2) setDataInto(): 객체화된 데이터를 DB에 삽입

@Override
	public int setDataInto() {
		ArrayList<OilInfo> oil = DataClass.oilInfoArray;
		try {
			Class.forName("oracle.jdbc.driver.OracleDriver");
			System.out.println("드라이버 로딩 성공");

			String url = "jdbc:oracle:thin:@127.0.0.1:1521:XE"; // Localhost의 접속 주소
			Connection conn = DriverManager.getConnection(url, "choonham", "6725"); // userName 과 password 로 로그인
			System.out.println("접속 성공!!");

			for (int i = 0; i < oil.size(); i++) {
				String query = "insert into oil_data (name, address, brand, phone, self, gasoilne, diesel)  values (?, ?, ?, ?, ?, ?, ?)";
				PreparedStatement pstmt = conn.prepareStatement(query); // 객체를 얻어온다.

				pstmt.setString(1, oil.get(i).getName());
				pstmt.setString(2, oil.get(i).getAddress());
				pstmt.setString(3, oil.get(i).getBrand());
				pstmt.setString(4, oil.get(i).getPhone());
				pstmt.setInt(5, oil.get(i).isSelf());
				pstmt.setInt(6, oil.get(i).getGasoline());
				pstmt.setInt(7, oil.get(i).getDiesel());

				pstmt.executeUpdate();
			}

			System.out.println("데이터 입력이 모두 완료되었습니다.");
			conn.close();
		} catch (Exception e) {
			System.out.println("데이터 입력 중 오류가 발생했습니다. 오류 로그: " + e.getMessage());
			return -1;
		}
		return 0;
	}

 3) makeTags(): DB의 데이터를 가져와 Tags 생성 & 셀프, 비셀프 주유소의 개수를 파악하여 출력

@Override
	public String makeTags() {
		String tags = "";
		int self = 0; // 셀프, 비셀프 주유소의 개수를 세기 위한 변수
		int noSelf = 0;
		tags += "<!doctype html> ";
		tags += "<html>";
		tags += "<head><title>Oil Data</title></head>";
		tags += "<body>";
		tags += "<table border='1'>";
		tags += "<tr>";
		tags += "<td>주유소 이름</td>";
		tags += "<td>주소</td>";
		tags += "<td>상호</td>";
		tags += "<td>전화번호</td>";
		tags += "<td>셀프 여부</td>";
		tags += "<td>휘발유</td>";
		tags += "<td>경유</td>";
		tags += "</tr>";
		try {
			Class.forName("oracle.jdbc.driver.OracleDriver");
			System.out.println("드라이버 로딩 성공!");

			String url = "jdbc:oracle:thin:@127.0.0.1:1521:XE"; // Localhost의 접속 주소
			Connection conn = DriverManager.getConnection(url, "choonham", "6725"); // userName 과 password 로 로그인
			System.out.println("접속 성공!!");

			Statement stmt = conn.createStatement(); // 쿼리문을 실행하기 위한 객체
			String query = "select * from oil_data";
			ResultSet rs = stmt.executeQuery(query);
			System.out.println("쿼리문 실행 완료!");

			while (rs.next()) {
				tags += "<tr>";

				tags += "<td>";
				tags += rs.getString("name");
				tags += "</td>";

				tags += "<td>";
				tags += rs.getString("address");
				tags += "</td>";

				tags += "<td>";
				tags += rs.getString("brand");
				tags += "</td>";

				tags += "<td>";
				tags += rs.getString("phone");
				tags += "</td>";

				tags += "<td>";
				if (rs.getInt("self") == 1) {
					tags += "Y";
					self++;
				} else {
					noSelf++;
					tags += "N";
				}
				tags += "</td>";

				tags += "<td>";
				tags += rs.getInt("gasoilne");
				tags += "</td>";

				tags += "<td>";
				tags += rs.getInt("diesel");
				tags += "</td>";
			}
			System.out.printf("셀프 주유소의 개수: %d | 비셀프 주유소의 개수: %d \n", self, noSelf);
			tags += "</table>";
			tags += "</body>";
			tags += "</html>";
			conn.close();
		} catch (Exception e) {
			System.out.println("데이터 읽기에 실패했습니다. 오류 로그:" + e.getMessage());
		}
		return tags;
	}

 4) makeHTML(String tags, String uri):

	@Override
	public void makeHTML(String tags, String uri) {
		FileWriter fw = null;
		try {
			fw = new FileWriter(uri);
			fw.write(tags);
			fw.close();
			System.out.println("HTML 파일 생성 완료!");
		} catch (IOException e) {
			System.out.println(e.getMessage());
		} finally {
			try {
				fw.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}

○MainClass:

package com.choonham;

import com.choonham.data.DataClass;
import com.choonham.util.MethodsClass;

public class MainClass {

	public static void main(String[] args) {
		String uri = "c:/filetest/oilData/oil.xls";
		MethodsClass ms = new MethodsClass();
		ms.readExcel(uri);
		ms.setDataInto();
		String tags = ms.makeTags();
		ms.makeHTML(tags, "c:/filetest/oilData/oil.html");
		// DataClass.checkData();
	}

}

○output:

결과 콘솔창
생성된 oil.html


 프로젝트의 Git:

github.com/Choonham/Choonham-2020.03.10-Spring-Class/tree/master/oilDB_choonham/src/com/choonham

 

Choonham/Choonham-2020.03.10-Spring-Class

Contribute to Choonham/Choonham-2020.03.10-Spring-Class development by creating an account on GitHub.

github.com

 

 

끝!!

Comments