3。下面是从文件中读取数据,并插入到数据库中,其中黑体字是关键语句,其他的代码,我主要是做了一些条件判断而已,这些大家可以根据自身的情况,进行调整。
public void setinsertStu(){//学生信息导入
String s="";
BufferedReader bufferIn=null;
try{
bufferIn = new BufferedReader(new InputStreamReader(new FileInputStream(mulu +"//" + fileName)));
DbConnect db = new DbConnect();
db.setLoadClass();
Connection conn = db.getMakeConnect();
Statement stmt = db.getMakeStatement(conn);
String sql = "";
ResultSet rs = null;
thisUrl fg = new thisUrl();
String[] jg = new String[3];
int i = 0;
int j = 1;
while ( (s = bufferIn.readLine()) != null) {
jg = fg.getfgStr(s,3);//分割数据
//判断导入学生所在的班级是否已经存在
sql = "select * from bj where bj_id like '" + jg[2] + "'";
rs = db.getMakeResultSet(stmt, sql);
if (rs.next()) { //班级存在,允许导入
//判断学生是否已经存在
sql = "select * from students where xh like '" + jg[0] + "'";
rs = db.getMakeResultSet(stmt, sql);
if (!rs.next()) {
sql = "insert into students (xh,xm,bj_id) values ('" + jg[0] + "','" +jg[1] + "','" + jg[2] + "')";
db.setUpdata(stmt, sql);
i++;
}
else {
msgInsert1 = msgInsert1 + j+". "+jg[0] + " 该学号已经存在!<br>";
}
db.setClose(rs);
}
else { //班级不存在
msgInsert1 = msgInsert1 + j+". "+ jg[0] + " 所在的班级不存在,请先设置班级信息!<br>";
}
j++;
}
db.setClose(stmt);
db.setClose(conn);
msgInsert2 ="<br>一共 " + (j-1) + " 条记录: " + i + " 条记录成功导入, " + (j-1 - i) +" 条记录导入失败!<br><br>";
}
catch (Exception edr) {
msgInsert1 = msgInsert1 + "<br>数据导入失败!<br>";
edr.printStackTrace();
}
try { //删除新文件
bufferIn.close();
File f3 = new File(mulu + "//" + fileName);
f3.delete();
}
catch (IOException e) {
msgInsert1 = msgInsert1 + "文件删除出错!";
}
msgInsert1="<font color=red>错误信息:</font><br>"+msgInsert1;
}