一段代碼,實現的功能是從Access資料庫讀取表資料,然後依次全部插入到JavaDB資料庫表中,類似於做拷貝.
import java.sql.*;
String sql_insert =null;//將sql_insert定義成全域變數,是為了出錯時,在catch部分能列印sql_insert內容,有助於調試.
ResultSet rs = null;
try {
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
String url = "jdbc:odbc:Driver={Microsoft Access Driver " +
"(*.mdb, *.accdb)};DBQ=path to database\\Database1.accdb";//紅色處應填入實際地址
Connection con = DriverManager.getConnection(url);
System.out.println("Connected!");
Statement stmt = null;
// SQL query command
String SQL = "SELECT * FROM data";
stmt = con.createStatement();
//stmt.execute(SQL);
rs = stmt.executeQuery(SQL);
String driver = "org.apache.derby.jdbc.ClientDriver";//在derby.jar裡面
//String dbName="EmbeddedDB";
String dbURL = "jdbc:derby://localhost:1527/PassWords;territory=zh_CN;user=admin;password=123456";// create=true表示當資料庫不存在時就建立它
try {
Class.forName(driver);
Connection conn = DriverManager.getConnection(dbURL);//啟動嵌入式資料庫
Statement st = conn.createStatement();
while(rs.next()){
byte[] bts=null;
String des = null;
String usname = null;
String psw = null;
String tips = null;
String other = null;
String ID = new String(rs.getBytes("ID"),"gbk");
int id = Integer.parseInt(ID);
bts = rs.getBytes("DESCRIPTION");
if(bts!=null )
des = new String(bts,"gbk");
bts = rs.getBytes("USERNAME");
if(bts !=null)
usname = new String(bts,"gbk");
bts = rs.getBytes("PASSWORD");
if(bts !=null)
psw = new String(bts,"gbk");
bts = rs.getBytes("TIPS");
if(bts !=null)
tips = new String(bts,"gbk");
bts = rs.getBytes("OTHERS");
if(bts != null)
other = new String(bts,"gbk");
sql_insert = "insert into APP.PSW(ID,DESCRIPTION,USERNAME,PASSWORD,TIPS,OTHERS) VALUES
("+id+",'"+des+"','"+usname+"','"+psw+"','"+tips+"','"+other+"')";
st.executeUpdate(sql_insert);//插入一條資料
}
} catch(Exception e){
System.out.println(sql_insert);
e.printStackTrace();
}
con.close();
} catch (SQLException e) {
System.out.println("SQL Exception: "+ e.toString());
} catch (ClassNotFoundException cE) {
System.out.println("Class Not Found Exception: "+
cE.toString());
}