Java之JDBC

來源:互聯網
上載者:User

串連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

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.