假設您已經把所有的資料由一個csv檔案匯入到Access 2007中的一個table (table name是test),然後依據欄位ID的值之不同,將所有ID相同之紀錄分別插入(Insert)到相同的資料表,不同的ID則放到不同的資料表中(table name為三位數字,由001開始,依序遞增)。由於不知道資料表可能有多少個,所以採用由程式動態建立。參考範例程式如下:
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.sql.Statement;
import java.sql.Timestamp;
public class DBAccess {
/**
* @param args
*/
public static void main(String[] args) {
try {
// Connect to database
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
String url = "jdbc:odbc:Driver={Microsoft Access Driver (*.mdb, *.accdb)};DBQ=C:/test/Database1.accdb";
Connection conn = DriverManager.getConnection(url, "", "");
// Fetch data from table
PreparedStatement pstmt = conn.prepareStatement("SELECT * FROM test");
ResultSet rs = pstmt.executeQuery();
ResultSetMetaData rsmd = rs.getMetaData();
int i = 0;
String oldID = "";
String tableName = "";
while (rs.next()) {
// Fetch a record
String ID = rs.getString("ID");
Timestamp diagnoseDate = rs.getTimestamp("看診日期");
String pulseCondition = rs.getString("脈象");
int segment = rs.getInt("段");
String chiefComplaint = rs.getString("主訴");
String disease = rs.getString("病名");
String prescription = rs.getString("配方");
// Change tableName if ID change
if (!oldID.equals(ID)) {
i++;
oldID = ID;
tableName = String.format("%03d", i);
System.out.println(tableName);
Statement stmt = conn.createStatement();
try {
// We may need to run this program several times
stmt.execute("DROP TABLE " + tableName);
} catch (SQLException se) {
// Just ignore the table does not exist exception
}
stmt.execute("CREATE TABLE " + tableName + " ([ID] CHAR(10), [看診日期] DATETIME, [脈象] TEXT, [段] INTEGER, [主訴] TEXT, [病名] TEXT, [配方] TEXT)");
for (int j = 1; j < rsmd.getColumnCount(); j++) {
System.out.print(rsmd.getColumnName(j) + "_");
}
System.out.println(rsmd.getColumnName(rsmd.getColumnCount()));
}
// Store each record into new table
String sql = "INSERT INTO " + tableName + " ([ID], [看診日期], [脈象], [段], [主訴], [病名], [配方]) VALUES(?, ?, ?, ?, ?, ?, ?)";
PreparedStatement pstmt2 = conn.prepareStatement(sql);
pstmt2.setString(1, ID);
pstmt2.setTimestamp(2, diagnoseDate);
pstmt2.setString(3, pulseCondition);
pstmt2.setInt(4, segment);
pstmt2.setString(5, chiefComplaint);
pstmt2.setString(6, disease);
pstmt2.setString(7, prescription);
pstmt2.executeUpdate();
}
rs.close();
pstmt.close();
conn.close();
} catch (Exception e) {
System.err.println("Got an exception!");
System.err.println(e.getMessage());
}
}
}
參考資料:
http://msdn.microsoft.com/en-us/library/bb208866%28v=office.12%29.aspx