Java——異常處理,資料庫連接

來源:互聯網
上載者:User

標籤: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——異常處理,資料庫連接

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.