JDBC的异常处理方式

A: try...catch(...) {...} finally {}

B: 关闭ResultSet,Statement , Connection


import java.sql.Connection;

import java.sql.DriverManager;

import java.sql.SQLException;

import java.sql.Statement;

 

public class ExceptionDemo {        

          public static void main(String[] args) {                   

                   Connection conn = null ;

                   Statement st = null ;                   

                   try {                            

                            // 注册驱动

                            Class.forName("com.mysql.jdbc.Driver") ;

                            // 获取连接对象

                            conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/mydb", "root", "1234") ;                            

                            // 获取执行sql的对象

                            st = conn.createStatement() ;                            

                            // 执行sql , 获取结果

                            String sql = "insert into user(uid , name , sal) values (1 , 'zhansgan' , 34.56)" ;

                            int count = st.executeUpdate(sql) ;                            

                            // 处理结果

                            System.out.println(count);

                   } catch (Exception e) {

                            e.printStackTrace() ;

                   } finally {            // 释放资源                            

                            if(st != null) {

                                      try {

                                               st.close() ;

                                      } catch (SQLException e) {

                                               e.printStackTrace();

                                      }

                            }

                           if(conn != null) {

                                      try {

                                               conn.close() ;

                                      } catch (SQLException e) {

                                               e.printStackTrace();

                                      }

                            }

                   }

          }

}
原文地址:https://www.cnblogs.com/loaderman/p/6415299.html