我正在从.csv文件导入数据库值。但是,.csv中的最后一行实际上是某些列的总和,而我的导入器使用最后一行更新数据库,这是不合需要的。这会弄乱我稍后会用它做的查询。请帮助我如何防止这种情况?
我的.csv导入程序的代码:
try
{
BufferedReader br=new BufferedReader(new FileReader("v.csv"));
String line;
while((line=br.readLine())!=null)
{
String[]value = line.split(",");
String sql = "INSERT into main ([Ticket #], Status, Priority, Department, [Account Name]) "
+ "values ('"+value[0]+"','"+value[1]+"','"+value[2]+"','"+value[3]+"','"+value[4]+"')";
System.out.println(sql);
PreparedStatement pst = null;
try
{
pst = db.prepareStatement(sql);
pst.executeUpdate();
}finally{
if(pst != null){
pst.close();
}
}
}
br.close();
}
catch(Exception e)
{
JOptionPane.showMessageDialog(null, e);
}
答案 0 :(得分:0)
试试这个:
try
{
BufferedReader br=new BufferedReader(new FileReader("v.csv"));
ArrayList<String> lines = new ArrayList<String>();
String line;
while((line=br.readLine())!=null)
{
lines.Add(line);
}
br.close();
if (lines.size() > 1) { // be sure that the last row exists (prevents indexoutexception)
for (int i = 0; i < lines.size() - 1; i++) { // the - 1 excludes the last row
String[]value = lines.get(i).split(",");
String sql = "INSERT into main ([Ticket #], Status, Priority, Department, [Account Name]) "
+ "values ('"+value[0]+"','"+value[1]+"','"+value[2]+"','"+value[3]+"','"+value[4]+"')";
System.out.println(sql);
PreparedStatement pst = null;
try
{
pst = db.prepareStatement(sql);
pst.executeUpdate();
} finally {
if(pst != null) {
pst.close();
}
}
}
}
}
catch(Exception e)
{
JOptionPane.showMessageDialog(null, e);
}
答案 1 :(得分:0)
如果可能,您可以使用Apache commons IO ReversedLinesFileReader并从最后读取CSV。然后你可以跳过第一行。
答案 2 :(得分:0)
试试这个:
try
{
BufferedReader br=new BufferedReader(new FileReader("v.csv"));
String line;
String firstFlag =true;
while((line=br.readLine())!=null)
{
if (!firstFlag){
String sql = "INSERT into main ([Ticket #], Status, Priority, Department, [Account Name]) "
+ "values ('"+value[0]+"','"+value[1]+"','"+value[2]+"','"+value[3]+"','"+value[4]+"')";
System.out.println(sql);
PreparedStatement pst = null;
try
{
pst = db.prepareStatement(sql);
pst.executeUpdate();
}finally{
if(pst != null){
pst.close();
}
}
}
String[]value = line.split(",");
firstFlag=false;
}
br.close();
}
catch(Exception e)
{
JOptionPane.showMessageDialog(null, e);
}