標籤:密碼 use orm close query java sql nal lin
1.基本參數
// JDBC 驅動名及資料庫 URL static final String JDBC_DRIVER = "com.mysql.jdbc.Driver"; //localhost:本地 static final String DB_URL = "jdbc:mysql://localhost:3306/mysql"; // 資料庫的使用者名稱與密碼,需要根據自己的設定 static final String USER = "root"; static final String PASS = "123456";
2.注入驅動串連資料庫,zzz_form表進行name檢索,關閉資料庫
try{ // 註冊 JDBC 驅動 Class.forName("com.mysql.jdbc.Driver"); // 開啟連結 System.out.println("串連資料庫..."); conn = DriverManager.getConnection(DB_URL,USER,PASS); // 執行查詢 System.out.println(" 執行個體化Statement對..."); stmt = conn.createStatement(); String sql; sql = "SELECT name FROM zzz_form"; ResultSet rs = stmt.executeQuery(sql); // 展開結果集資料庫 while(rs.next()){ // 通過欄位檢索 String name = rs.getString("name"); myNameList.add(name); System.out.println(name); } // 完成後關閉 rs.close(); stmt.close(); conn.close(); }catch(SQLException se){ // 處理 JDBC 錯誤 System.out.print("處理 JDBC 錯誤"); se.printStackTrace(); }catch(Exception e){ // 處理 Class.forName 錯誤 System.out.print("處理 Class.forName 錯誤"); e.printStackTrace(); }finally{ // 關閉資源 try{ if(stmt!=null) stmt.close(); }catch(SQLException se2){ }// 什麼都不做 try{ if(conn!=null) conn.close(); }catch(SQLException se){ se.printStackTrace(); } }
說明:
1.匯入庫 mysql-connector-java-5.1.42-bin.jar
JAVA連結MYSQL