利用元資料編寫查詢的通用方法
阿新 • • 發佈:2019-02-09
import java.io.InputStream; import java.sql.Connection; import java.sql.DriverManager; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; import java.util.Properties; public class JDBCTools { public static void update1(String sql , Object ... args){ Connection con = null; PreparedStatement ps = null; try { con = getConnection(); ps = con.prepareStatement(sql); for(int i = 0;i<args.length;i++){//索引的下標從1開始 和陣列不一樣 ps.setObject(i+1, args[i]); } ps.executeUpdate(); } catch (Exception e) { e.printStackTrace(); }finally{ release(con, ps); } } public void update(String sql){//實現資料庫的更新操作 使用Statement介面 Connection con = null; Statement state = null; try { con = getConnection(); state = con.createStatement(); state.executeUpdate(sql); } catch (Exception e) { e.printStackTrace(); }finally{ release(con,state); } } public static Connection getConnection() throws Exception{//連線資料庫 String driverClass = null; String url = null; String user = null; String password = null; Properties properties = new Properties(); InputStream in = Review.class.getClassLoader().getResourceAsStream("jdbc.properties"); properties.load(in); driverClass = properties.getProperty("driver"); url = properties.getProperty("jdbcurl"); user = properties.getProperty("user"); password = properties.getProperty("password"); Class.forName(driverClass); return DriverManager.getConnection(url, user, password); } public static void release(Connection con , Statement state){//關閉資料庫連線 if(state != null){ try { state.close(); } catch (SQLException e) { e.printStackTrace(); } } if(con != null){ try { con.close(); } catch (SQLException e) { e.printStackTrace(); } } } public static void release(ResultSet rs , Connection con , Statement state){//關閉資料庫連線 if(rs != null) { try { rs.close(); } catch (SQLException e) { e.printStackTrace(); } } if(state != null){ try { state.close(); } catch (SQLException e) { e.printStackTrace(); } } if(con != null){ try { con.close(); } catch (SQLException e) { e.printStackTrace(); } } } }