2011-08-18 95 views
-1

我有一个用~1000行Java代码编写的类,它将一个数据库迁移到另一个数据库。 它有19个方法用于复制每个表,1个负载是Filemaker的特殊JDBC驱动程序。删除重复的Java代码

我在看着这个,不禁想到我在这里真的很愚蠢,只是让我的催促从onActionPerformed调用几个方法来管理'设计'。我修剪了我所能做的,但它仍然看起来很重要。

所以这里的要点是:

public static void companyInsert() throws SQLException{ 
// This loads the JDBC drivers, gets the connections, turns off auto commit and returns a createStatement() 
query = classname.Connect(); 

try { 
    results = query.executeQuery("SELECT * from table"); 

    // Iterate through the results and print them to standard output 
System.out.println("Starting Customers"); 

stmt = con.prepareStatement("INSERT ignore INTO table (idone, idtwo) values (?, ?)"); 

while (results.next()) { 
    String fname = results.getString("field 1"); 
    String lname = results.getString("field 2"); 
// System.out.println("Found user \"" + fname + " " + lname + "\""); 
    stmt.setString(1, fname); 
    stmt.setString(2, lname); 
    stmt.addBatch(); 
    } 
    // submit the batch for execution 
    int[] updateCounts = stmt.executeBatch(); 
    System.out.println("Update count: " + updateCounts); 
    con.commit(); 
    stmt.close(); 
    System.out.println("Completed Customers"); 
} 
catch (BatchUpdateException be) { 
//handle batch update exception 
int[] counts = be.getUpdateCounts(); 
for (int i = 0; i < counts.length; i++) { 
    System.out.println("Statement["+i+"] :"+counts[i]); 
} 
con.rollback(); 
}catch (SQLException e) { 

//handle SQL exception 
con.rollback(); 
} 
} 

有这些方法中的19个,只有SQL部分改变(也有更多的领域被设置为其他记录,有些也被检索的日期)。希望有人有一些好主意 - 如果我可以把那个catch部分撕掉(这总是相同的),那就足够了!

+0

这是一次性代码吗? – Augusto

+4

你有没有听说过ORM和/或Hibernate和/或JPA?它确实是这样做的(删除JDBC样板)。 – BalusC

+0

同意BalusC。 JPA现在是在Java中使用数据库的标准方式。我偶尔使用JDBC仅用于核心传统SQL选择。使用JPA将令人难以置信地减少您当前的代码。 –

回答

1

一个简单的方法是有一个异常处理程序...

private void handleException(Exception e, Connection con) throws SQLException { 
    if (e instanceof BatchUpdateException) { 
     BatchUpdateException be = (BatchUpdateException) e; 
     //handle batch update exception 
     int[] counts = be.getUpdateCounts(); 
     for (int i = 0; i < counts.length; i++) { 
      System.out.println("Statement["+i+"] :"+counts[i]); 
     } 
     con.rollback(); 
    } 
    else if (e instanceof SQLException) { 
     con.rollback(); 
    } 
} 

...然后你的代码做这个:

try { 
    //... jdbc code 
} 
catch (Exception e) { 
    handleException(e, con); 
} 

...或者你可以走了更多的重构和应用设计模式,如'模板方法'。

+0

我结束了使用这种异常处理方法与模板方法结合起来,感谢加载给每个人的贡献! –