標籤:exception one als imp 需要 state bool test 異常處理
在學習資料庫連接時看到try(){}結構,查了一下寫在這裡:
1 import java.sql.Connection; 2 import java.sql.DriverManager; 3 import java.sql.ResultSet; 4 import java.sql.Statement; 5 6 /** 7 * Created by BoGummyYoung on 2017/4/6. 8 */ 9 public class ConnMySql10 {11 public static void main(String[] args) throws Exception12 {13 //1.載入驅動,使用反射知識,現在記住這麼寫14 Class.forName("com.mysql.jdbc.Driver");15 try(16 //2.使用DriverManager擷取資料庫連接17 //其中返回的Connection就代表了Java程式和資料庫的串連18 //不同資料庫的URL寫法需要查驅動文檔,使用者名稱、密碼由DBA分配19 Connection conn = DriverManager.getConnection(20 "jdbc:mysql://localhost:3306/select_test"21 ,"root","bogummy");22 //3.使用Connection來建立一個Statement對象23 Statement stmt = conn.createStatement();24 //4.執行SQL語句25 /*26 Statement 有三種執行SQL語句的方法:27 1.execute()可執行任何SQL語句——返回一個boolean值28 如果執行後第一個結果是ResultSet,則返回true,否則返回false29 2.executeQuery()執行select語句——返回查詢到的結果集30 3.executeUpdate()用於執行DML語句——返回一個整數31 代表被SQL語句影響的記錄條數32 */33 ResultSet rs = stmt.executeQuery("select s.*, teacher_name"34 +" from student_table s , teacher_table t"35 +" where t.teacher_id = s.java_teacher"))36 {37 //ResultSet有一系列的getXxx(列索引 | 列名)方法,用於擷取記錄指標38 //指向行、列特定的值,不斷地使用next()將記錄指標下移一行39 //如果移動之後記錄指標依然指向有效行,則next()方法返回true40 while(rs.next())41 {42 System.out.println(rs.getInt(1) + "\t"43 + rs.getString(2) + "\t"44 + rs.getString(3) + "\t"45 + rs.getString(4) + "\t");46 }47 }48 }49 }View Code
基本的異常處理:
1 try2 {3 //業務實現代碼4 ...5 }6 catch ( )
Java——異常處理,資料庫連接