//import necessary JDBC drivers
import java.sql.*;
import java.util.*;
import java.io.*;
public class csvTest2
{
private static BufferedReader stdin = new BufferedReader(new InputStreamReader(System.in));
public static void main(String args[]) throws IOException
{
String url = "jdbc:mysql://localhost:3306/"; //MySQL URL
String dbName = ""; //Declare Database Name variable
String usr = ""; //Declare User variable
String pwd = ""; //Declare Password variable
String csvName = "c:\data\test.csv";
Connection db = null;
Statement stmt = null;
ResultSet rs = null;
ArrayList bookList = new ArrayList();
HashMap bookMap = null;
FileWriter fw = null;
//MySQL 유저 아이디
System.out.print("User name: ");
usr = stdin.readLine();
//MySQL 유저 암호
System.out.print("Password: ");
pwd = stdin.readLine();
//MySQL 데이터베이스명
System.out.print("Database name: ");
dbName = stdin.readLine();
//확인삼아 유저 정보 출력
System.out.println("\n=======================\n" +
"User Input Information\n=======================\nUser name: " + usr);
System.out.println("Password: " + pwd);
System.out.println("Database name: " + dbName);
//MySQL 접속
url = url + dbName;
try
{
try
{
//Connect to MySQL with user input
Class.forName("org.gjt.mm.mysql.Driver");
System.out.println("Connecting to " + url);
System.out.println("==========================================" +
"====================");
db = DriverManager.getConnection(url, usr, pwd);
stmt = db.createStatement();
//MySQL 명령어
rs = stmt.executeQuery("SELECT * FROM dbPet;");
//MySQL안에 데이터 읽기
while(rs.next())
{
bookMap = new HashMap();
bookMap.put("item1", rs.getString(1));
bookMap.put("item2", rs.getString(2));
bookMap.put("item3", rs.getString(3));
bookMap.put("item4", rs.getString(4));
bookMap.put("item5", rs.getString(5));
bookMap.put("item6", rs.getString(6));
bookList.add(bookMap);
}
} catch(SQLException sqle)
{
sqle.printStackTrace();
}
finally
{
if(rs != null) {try{rs.close();}catch(Exception e){}}
if(stmt != null) {try{stmt.close();}catch(Exception e){}}
if(db != null) {try{db.close();}catch(Exception e){}}
}
fw = new FileWriter(csvName);
//콤마 (,) 상입
for(Iterator i = bookList.iterator(); i.hasNext();)
{
String line = "";
bookMap = (HashMap)i.next();
line = (String)bookMap.get("item1") + ",";
line += (String)bookMap.get("item2") + ",";
line += (String)bookMap.get("item3") + ",";
line += (String)bookMap.get("item4") + ",";
line += (String)bookMap.get("item5") + ",";
line += (String)bookMap.get("item6") + ",";
System.out.println(line);
fw.write(line + "\r\n");
}
} catch(Exception ex){
ex.printStackTrace();
} finally {
if(fw != null){try{fw.close();}catch(Exception e){}}
}
}
}
[출처] 자바로 csv 파일생성|작성자 앵주씨
'프로그래밍 > java' 카테고리의 다른 글
자바 인코딩 관련 (0) | 2010.04.15 |
---|---|
자바 텍스트 파일 이어쓰기 (0) | 2010.04.15 |
자바 CSV 파일 생셩 (0) | 2010.04.15 |
Java Application, jar 압축 및 윈도우 .execute 로 래핑 (0) | 2009.12.14 |
자바 애플리케이션에서 동적으로 PDF 파일 생성하기(한글 적용) (0) | 2009.07.02 |