我有一個用~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部分撕掉(這總是相同的),那就足夠了!
這是一次性代碼嗎? – Augusto
你有沒有聽說過ORM和/或Hibernate和/或JPA?它確實是這樣做的(刪除JDBC樣板)。 – BalusC
同意BalusC。 JPA現在是在Java中使用數據庫的標準方式。我偶爾使用JDBC僅用於核心傳統SQL選擇。使用JPA將令人難以置信地減少您當前的代碼。 –