JDBC連結資料庫
阿新 • • 發佈:2018-12-10
學習記錄:複習
JDBC簡單鏈接資料庫
/** 關閉資源用 */ Connection conn = null; Statement stmt = null; ResultSet rest = null; /** 設定url,user,password,sql */ String url = "jdbc:mysql://localhost:3306/kevin?useUnicode=true&characterEncoding=utf-8"; String user = "root"; String password = "123456"; String sql = "select * from blog"; try { // 註冊驅動 Class.forName("com.mysql.jdbc.Driver"); // 獲得資料庫連結 conn = DriverManager.getConnection(url, user, password); // 獲得Statement stmt = conn.createStatement(); rest = stmt.executeQuery(sql); while (rest.next()) { System.out.println(rest.getString("title") + "_" + rest.getString("viceTitle")); } } catch (Exception e) { System.err.println("發生異常:"+e); } finally {//關閉資源 rest.close(); stmt.close(); conn.close(); }
關閉資源放在finally中