2013年11月1日 星期五

java-template java-read-mysql-to-text-file mysql2file




mysql2file.java

import java.sql.*;
import java.net.*;
import java.io.*;
import java.util.*;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.FileNotFoundException;
import java.io.IOException;
public class mysql2file {

public static String padL(String s, int n,char t) {
return String.format("%1$" + n + "s", s).replace(' ', t);
}


public static String padR(String s, int n,char t) {
return String.format("%1$-" + n + "s", s).substring(0, n).replace(' ', t);
    }



public static void main( String argv[] ) {
go();
public static void go(){ 
FileOutputStream fop = null;
File file;
String content = "This is the text content";
try{
file = new File("/folder/targetFile.txt");
fop = new FileOutputStream(file);
if (!file.exists()) {
file.createNewFile();
}
  String result="";
ResultSet rs = null;
Connection con = null;
Statement stmt = null;
Class.forName("com.mysql.jdbc.Driver");
con = DriverManager.getConnection("jdbc:mysql://localhost/hr?useUnicode=true&characterEncoding=UTF8","UserName", "UserPassWord");
stmt = con.createStatement();
String sqlString="select recordid from SourceTableName;";
rs = stmt.executeQuery(sqlString);
while (rs.next()){
System.out.println(rs.getString(1));
byte[] contentInBytes = rs.getString(1).getBytes();
fop.write(contentInBytes);
fop.flush(); 
fop.close();
}catch (Exception e) {
e.printStackTrace();
}
}

沒有留言:

張貼留言