/**
 * 导入
 */
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);

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

解决方案 »

  1.   

    连接,我没bean、怎么插?我导出的时候是下面这种
    colId,sid,id,colCode,colName,colPid,colLevel,colType,colLenght,colDate,com_id,display,formula,isText,
    75122,2,6763,BQSJ,期末数|||实际数,0,75122,0,0,2010-07-26 10:51:54.193,1,1,null,0,
    75123,10,6763,BNNC,年初数,0,75123,0,0,2010-07-26 10:51:54.193,1,1,null,0,现在我要导入。读取第一行来做为列名、 insert的时候怎么写?
      

  2.   

    public void ExportOutTableTest(String str) {
    JFileChooser chooser = new JFileChooser();
    chooser.showOpenDialog(this);
    File file = chooser.getSelectedFile();
    String fileName = file.getName();
    if (fileName != null && fileName.trim().length() > 0) {
    if (!(fileName.endsWith(".txt"))) {
    fileName = fileName.concat(".txt");
    }
    }
    file = new File(file.getParent().concat(file.separator).concat(fileName));
    if (file.exists()) {
    int i = JOptionPane.showConfirmDialog(this, "该文件已经存在,确定要覆盖吗?");
    if (i != JOptionPane.YES_OPTION) {
    return;
    }
    }
    try {
    file.createNewFile();
    FileWriter fw = new FileWriter(file);
    fw.write(str);
    fw.flush();
    fw.close();
    } catch (IOException e) {
    // JOptionPane.showMessageDialog(null, e.getMessage(), "错误信息",JOptionPane.WARNING_MESSAGE);
    JOptionPane.showMessageDialog(null,"导出失败!");
    return ;
    }
    return;
    }public String DBMessage(String tableName,long id) {
    // public String DBMessage(long id){
    String dbdriver = "com.microsoft.sqlserver.jdbc.SQLServerDriver";
    String url = "jdbc:sqlserver://localhost:3333;databaseName=aidb";
    String us = "sa";
    String pw = "sa";
    String sql = "select * from "+tableName+" where id=" + id + "";
    // String sql = "select * from ColumnItem where id="+id+""; Connection conn = null;
    Statement stat = null;
    ResultSet rs = null;
    StringBuffer sb = new StringBuffer(); try {
    Class.forName(dbdriver);
    conn = DriverManager.getConnection(url, us, pw);
    stat = conn.createStatement();
    rs = stat.executeQuery(sql);
    ResultSetMetaData rsmd = rs.getMetaData();
    int counts = rsmd.getColumnCount();
    String[] str = new String[counts]; for (int col = 0; col < counts; col++) {
    String colname = rsmd.getColumnName(col + 1);
    str[col] = colname;
    sb.append(str[col]);
    sb.append(",");
    }
    sb.append("\r\n");
    while (rs.next()) {
    for (int cols = 0; cols < str.length; cols++) {
    String value = rs.getString(str[cols]);
    // String values = value.trim();
    sb.append(value);
    sb.append(",");
    }
    sb.append("\r\n");
    }
    } catch (ClassNotFoundException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
    } catch (SQLException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
    }
    return sb.toString();
    }
    上面是一个导出的JDBC和业务逻辑。导入的业务逻辑以及写好了,
    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();
    }
    }
    }
    }
    文件已经能读到了,我怎么把文件的内容插入到数据中?
      

  3.   

    colId,sid,id,colCode,colName,colPid,colLevel,colType,colLenght,colDate,com_id,display,formula,isText,你数据库有这样的表吗,这么多字段
      

  4.   

    colId,sid,id,colCode,colName,colPid,colLevel,colType,colLenght,colDate,com_id,display,formula,isText,
    75122,2,6763,BQSJ,期末数|||实际数,0,75122,0,0,2010-07-26 10:51:54.193,1,1,null,0,
    75123,10,6763,BNNC,年初数,0,75123,0,0,2010-07-26 10:51:54.193,1,1,null,0,如果你的表,一行插入到数据库一条数据 就很简单,你的表是什么样的,需要什么字段
      

  5.   

    colId,sid,id,colCode,colName,colPid,colLevel,colType,colLenght,colDate,com_id,display,formula,isText  这就是表结构。 读的哪个TXT文件,那么表结构就是怎么样...
      

  6.   

    读的TXT文件的第一行就是表结构,然后下面的数据就循环插入
      

  7.   


    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怎么转换。具体情况具体分析