package jdbc.jdbc; import java.sql.Connection; import java.sql.DriverManager; import java.sql.ResultSet; import java.sql.Statement; /** * 第一個JDBC * @author noteless */ public class FirstJDBC { public static void main(String[] args) throws Exception { //一、註冊驅動 Class.forName("com.mysql.jdbc.Driver"); //數據庫鏈接所需參數 String user = "root"; String password = "123456"; String url = "jdbc:mysql://localhost:3306/sampledb?useUnicode=true&characterEncoding=utf-8"; //二、獲取鏈接對象 Connection conn = DriverManager.getConnection(url, user, password); //設置sql語句 String sql = "select * from student"; //三、得到sql語句執行對象 Statement stmt = conn.createStatement(); //四、執行sql並保存結果集 ResultSet rs = stmt.executeQuery(sql); //五、處理結果集 while (rs.next()) { System.out.print("id:" + rs.getInt(1)); System.out.print(",姓名:" + rs.getString(2)); System.out.print(",年齡:" + rs.getInt(3)); System.out.println(",性別:" + rs.getString(4)); } //六、資源關閉 rs.close(); stmt.close(); conn.close(); } }
package jdbc; import java.sql.Connection; import java.sql.DriverManager; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; public class FirstJDBCFormal { public static void main(String[] args) throws Exception { //一、註冊驅動 Class.forName("com.mysql.jdbc.Driver"); //數據庫鏈接所需參數 String user = "root"; String password = "123456"; String url = "jdbc:mysql://localhost:3306/sampledb?useUnicode=true&characterEncoding=utf-8"; Connection conn = null; Statement stmt = null; ResultSet rs = null; try { //二、獲取鏈接對象 conn = DriverManager.getConnection(url, user, password); //三、設置sql語句 String sql = "select * from student"; //四、得到sql語句執行對象 stmt = conn.createStatement(); //五、執行並保存結果集 rs = stmt.executeQuery(sql); //六、處理結果集 while (rs.next()) { System.out.print("id:" + rs.getInt(1)); System.out.print(",姓名:" + rs.getString(2)); System.out.print(",年齡:" + rs.getInt(3)); System.out.println(",性別:" + rs.getString(4)); } } catch (Exception e) { throw new RuntimeException(e); } finally { //七、資源關閉 try { if (conn != null) { conn.close(); } if (rs != null) { rs.close(); } if (stmt != null) { stmt.close(); } } catch (SQLException e) { } } } }
if (conn != null) { try{ conn.close(); }catch (SQLException e){ } } if (rs != null) { try{ rs.close(); }catch (SQLException e){ } } if (stmt != null) { try{ stmt.close(); }catch (SQLException e){ } }
try{ //... }catch(SQLException ex) { while(ex != null) { System.out.println("SQLState:" + ex.getSQLState()); System.out.println("Error Code:" + ex.getErrorCode()); System.out.println("Message:" + ex.getMessage()); Throwable t = ex.getCause(); while(t != null) { System.out.println("Cause:" + t); t = t.getCause(); } ex = ex.getNextException(); } }
try{ //... }catch(SQLException ex) { for(Throwable e : ex ) { System.out.println("Error encountered: " + e); } }