串連MySQL資料庫:建表-導包-建立資料庫封裝類-建立實體類-建立資料庫訪問層介面及實現-建立資料庫介面訪問層工廠類
util/DBConnection.java中定義串連MySQL的基本資料,提供串連和中斷連線的方法。
private static final String DBDRIVER = "com.mysql.jdbc.Driver";private static final String DBURL = "jdbc:mysql://localhost:3306/shop";private static final String USERNAME = "root";private static final String PASSWORD = "root";public static Connection getConnection() {Connection conn = null;try {Class.forName(DBDRIVER);conn = DriverManager.getConnection(DBURL);} catch (ClassNotFoundException e) {e.printStackTrace();} catch (SQLException e) {e.printStackTrace();}return conn;}public static void close(Connection conn) {if (conn != null) {try {conn.close();} catch (SQLException e) {e.printStackTrace();}}}public static void close(PreparedStatement pstmt) {if (pstmt != null) {try {pstmt.close();} catch (SQLException e) {e.printStackTrace();}}}public static void close(ResultSet rs) {if (rs != null) {try {rs.close();} catch (SQLException e) {e.printStackTrace();}}}
在bean/下建立實體類xx.java,成員變數設定成private,並添加get和set方法。
在dao/下建立資料庫提供者xxDAO.java和實現xxDAOImpl.java
在factory/下建立資料庫訪問層工廠xxDAOFactory.java,添加擷取資料庫訪問層實現的方法對象。
public static CommodityDAO createCommodityDAOImpl(){return new CommodityDAOImpl();
用PrepareStatement不用Statement http://wenku.baidu.com/view/ccb9da020740be1e650e9abc.html