日期:2014-05-20 浏览次数:20821 次
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怎么转换。具体情况具体分析