假设sqlserver数据库DatabaseName=master,user = "sa",password = "root"
数据库中表temperature中group,layer列为int类型,one,two,three,four列为float类型
源文件名为sourcefile.txt
我用正则表达式,帮你把数据导入到SQLServer中了,完整的Java程序如下:
import java.io.BufferedReader;
import java.io.FileNotFoundException;
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.util.regex.Matcher;
import java.util.regex.Pattern;
public class CCA {
//SQLServer
private String driverName = "com.microsoft.jdbc.sqlserver.SQLServerDriver";//加载驱动程序
private String url = "jdbc:microsoft:sqlserver://localhost:1433;DatabaseName=master";//设置数据库连接串 master为数据库名
private String user = "sa";//数据库登录用户名
private String password = "root";//数据库登录密码
public Connection getConnection() {
try {
Class.forName(driverName);
return DriverManager.getConnection(url, user, password);
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
public static void main(String[] args) {
CCA dcm = new CCA();
String sql = "insert into temperature(group,layer,one,two,three,four) values(?,?,?,?,?,?)";
Connection conn=null;
PreparedStatement ps=null;
BufferedReader br=null;
try {
conn = dcm.getConnection();
br=new BufferedReader(new FileReader("sourcefile.txt"));
String s="";
String regex="(\\d+)\\s+(\\d+)\\s+(\\d+\\.\\d+)\\s+(\\d+\\.\\d+)\\s+(\\d+\\.\\d+)\\s+(\\d+\\.\\d+)";
while((s=br.readLine())!=null){
s=s.trim();
Pattern p=Pattern.compile(regex);
Matcher m=p.matcher(s);
if(m.matches()){
//System.out.println(m.group(1)+" "+m.group(2)+" "+m.group(3)+" "+m.group(4)+" "+m.group(5)+" "+m.group(6));
ps=conn.prepareStatement(sql);
ps.setInt(1, Integer.parseInt(m.group(1)));
ps.setInt(2, Integer.parseInt(m.group(2)));
ps.setFloat(3, Float.parseFloat(m.group(3)));
ps.setFloat(4, Float.parseFloat(m.group(4)));
ps.setFloat(5, Float.parseFloat(m.group(5)));
ps.setFloat(6, Float.parseFloat(m.group(6)));
ps.executeUpdate();
}
}
System.out.println("数据插入完毕!");
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}catch (SQLException e) {
e.printStackTrace();
}finally{
try {
ps.close();
conn.close();
br.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
运行结果:
数据插入完毕!
我看你这个文本格式有点像csv文本格式,你试下将txt格式改成csv然后用excel打开能不能看到数据分列展示,如何可以,那么恭喜你这个csv文件可以直接导入到sqlserver