第一步:連接MySQL數據庫:public class DBOpenHelper { private static String driver = "com.mysql.jdbc.Driver";// MySQL驅動 private static String url = "jdbc:mysql://IP:xxxx/數據庫";//MYSQL數據庫連接Url private static String user = "root";//用戶名 private static String password = "root";//密碼 //連接數據庫 public static Connection getConn(){ Connection conn = null; try { Class.forName(driver);//獲取MYSQL驅動 conn = (Connection) DriverManager.getConnection(url, user, password);//獲取連接 } catch (ClassNotFoundException e) { e.printStackTrace(); } catch (SQLException e) { e.printStackTrace(); } return conn; } //關閉數據庫 public static void closeAll(Connection conn, PreparedStatement ps){ if (conn != null) { try { conn.close(); } catch (SQLException e) { e.printStackTrace(); } } if (ps != null) { try { ps.close(); } catch (SQLException e) { e.printStackTrace(); } } } //關閉數據庫 public static void closeAll(Connection conn, PreparedStatement ps, ResultSet rs){ if (conn != null) { try { conn.close(); } catch (SQLException e) { e.printStackTrace(); } } if (ps != null) { try { ps.close(); } catch (SQLException e) { e.printStackTrace(); } } if (rs != null) { try { rs.close(); } catch (SQLException e) { e.printStackTrace(); } } }}第二步:MySQL數據庫操作: public class DBService { private Connection conn=null; //打開數據庫對象 private PreparedStatement ps=null;//操作整合sql語句的對象 private ResultSet rs=null;//查詢結果的集合 //DBService 對象 public static DBService dbService=null; // 構造方法,私有化 private DBService(){ } //獲取MySQL數據庫單例類對象 public static DBService getDbService(){ if(dbService==null){ dbService=new DBService(); } return dbService; } // 獲取數據 public List
網站導航
- zblogPHP模板zbpkf
- zblog免費模板zblogfree
- zblog模板學習zblogxuexi
- zblogPHP仿站zbpfang