JAVA在原有資料庫通訊的基礎上新增與Access資料庫的簡單通訊
阿新 • • 發佈:2018-11-04
第一步:首先我們需要寫一個Access資料庫介面連線類
/** * Created by Knigh on 2017/6/26. */ public class AccessJoinAction { Connection con = null; Statement s = null; ResultSet rs=null; /*連線*/ public Connection getConnection(){ try { // 載入JDBC-ODBC橋驅動程式 Class.forName("sun.jdbc.odbc.JdbcOdbcDriver"); // 方式一 通過驅動聯接 con=DriverManager.getConnection("jdbc:odbc:driver={Microsoft Access Driver (*.mdb)};DBQ=***.mdb; pwd=******"); // 方式二 通過資料來源與資料庫建立連線 //con = DriverManager.getConnection("jdbc:odbc:AccessDatabase"); } catch (Exception e) { e.printStackTrace(); } return con; } /*關閉資料來源*/ public void CloseConnection(Connection con,ResultSet rs,Statement s){ try { if (rs!=null) { rs.close(); } if (s!=null) { s.close(); } if (con!=null) { con.close(); } } catch (SQLException e) { e.printStackTrace(); } } }
第二步:我們寫具體的增刪改查方法類繼承第一步的連線類,通過main方法可測試資料
/** * Created by Knigh on 2017/6/26. */ public class AccessAction extends AccessJoinAction { Connection con = null; Statement s = null; ResultSet rs=null; public String seach(Integer taskID,Integer status){ String isOK = null; try { con=getConnection(); s = con.createStatement(); rs=s.executeQuery("select `TaskID`,`conTent1` from Task_MCGS order by `TaskID` "); while (rs.next()) { Integer a = rs.getInt("TaskID"); String b = rs.getString("conTent1"); if((a > taskID) && (status == 2) ){ isOK = a + "-" + b; break; }else{ } } System.out.println("查詢結束"); } catch (Exception e) { e.printStackTrace(); } finally { CloseConnection(con, rs, s); } return isOK; } public void add(String code,Integer taskID, Integer partOK,Integer partNOK,String time){ try { int result=0; con=getConnection();//呼叫繼承類 方法 s = con.createStatement();// 建立SQL語句物件 result=s.executeUpdate("INSERT INTO OpHist_MCGS(`ProdName`,`EquipOpRelID`,`IsCompleted`,`UserChar2`,`UserChar3`,`IsOK`,`IsNOK`,`MCGS_Time`)VALUES('"+code+"',15,1,'"+code+"',"+taskID+","+partOK+","+partNOK+",'"+time+"')"); if (result>0) { System.out.println("新增成功"); } } catch (Exception e) { e.printStackTrace(); } finally { CloseConnection(con, rs, s); } } public void updata(){ try { int result=0; con=getConnection(); s = con.createStatement(); result=s.executeUpdate("update Table1 set name='aa' where id=1"); if (result>0) { System.out.println("修改成功"); } } catch (Exception e) { e.printStackTrace(); } finally { CloseConnection(con, rs, s); } } public void delete(){ try { int result=0; con=getConnection(); s = con.createStatement(); result=s.executeUpdate("delete from Table1 where id=3"); if (result>0) { System.out.println("刪除成功"); } } catch (Exception e) { e.printStackTrace(); } finally { CloseConnection(con, rs, s); } } public static void main(String[] args) { AccessAction accessAction=new AccessAction(); // accessAction.seach(); accessAction.add("adwadwadaw",120,0,1, "2017-09-08 08:19:10"); // accessAction.updata(); // accessAction.delete(); } }