日期:2014-05-20  浏览次数:20821 次

文件导入到数据库
/**
* 导入
*/
public void ImportTableTest(String TableName) {
Reader reader = null;
try {
char[] tempchars = new char[30];
int charread = 0;
reader = new InputStreamReader(new FileInputStream(TableName));

while ((charread = reader.read(tempchars)) != -1) {
if ((charread == tempchars.length) && (tempchars[tempchars.length - 1] != '\r')) {
System.out.print(tempchars);
} else {
for (int i = 0; i < charread; i++) {
if (tempchars[i] == '\r') {
continue;
} else {
System.out.print(tempchars[i]);
}
}
}
}
} catch (Exception e1) {
e1.printStackTrace();
} finally {
if (reader != null) {
try {
reader.close();
} catch (IOException e1) {
e1.getMessage();
}
}
}
}

/**
* 事件
*/
public void actionPerformed(ActionEvent e){
// TODO Auto-generated method stub
if(e.getActionCommand().equals("...")){
try {
new Import().FileChooser();
} catch (Exception e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
}else if(e.getActionCommand().equals("导入")){
String str=jtextFiledImport.getText();
new Import().ImportTableTest(str);

}
}
“...”是选择文件路径的,点击导入调用最上面那个方法。现在文件我已经读到了、并可打印到控制台,我还需要怎么样才能导入到数据库中?

------解决方案--------------------
Java code

data.txt
/////////////
id,usename,pdate
1,test1,2012-04-01 17:31:18.0
2,test2,2012-04-01 17:31:31.0
3,test3,2012-04-01 17:31:40.0
/////////////
数据库表/ test下表t
create table t(id int primary key,usename varchar(20),pdate datetime);
////////////
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.sql.Timestamp;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

public class Writer {
    public static void main(String[] args) throws IOException, ClassNotFoundException, SQLException {
        File f = new File("data.txt");
        BufferedReader bf = new BufferedReader(new FileReader(f));
        
        String driver = "com.mysql.jdbc.Driver";
        String url = "jdbc:mysql://localhost/test";
        String user = "root";
        String password = "admin";
        Connection conn = null;
            Class.forName(driver);
            conn = DriverManager.getConnection(url, user, password);
            String sql = "insert into t values(?,?,?)"; 
            //必须了解列名属性,假如列名属性已知;
            
            String[] columnNames =null;
            List<String[]> lists = new ArrayList<String[]>();
            String str = null;
            int count = 0;
            PreparedStatement pst = conn.prepareStatement(sql);
            while ((str = bf.readLine())!= null){
                if(count == 0){
                    columnNames = str.split(",");
                }
                else{
                    String s[] = str.split(",");
System.out.println(s.length);//验证是不是和你的列名数相等
                    lists.add(s);
                    
                    pst.setInt(1, Integer.parseInt(s[0].trim()));
                    pst.setString(2, s[1].trim());
                    String s1 = s[2].replace("\\.\\d+", "");
                    String DEFAULT_FORMAT = "yyyy-MM-dd HH:mm:ss.SSSS";
                    SimpleDateFormat sdf = new SimpleDateFormat(DEFAULT_FORMAT);
                    Date date = null;
                    try {
                        date = sdf.parse(s[2]);
                    } catch (ParseException e){
                        e.printStackTrace();
                    }
                    pst.setTimestamp(3,new Timestamp(date.getTime()));
                    pst.addBatch();
                    
                }
                count++;
            }
            pst.executeBatch();
            pst.close();
            conn.close();
    }
}
//实例,里面有3种类型,你对照写。int,string,timeStamp怎么转换。具体情况具体分析