JDBC异常
异常处理允许我们以受控的方式处理异常情况,而不是直接退出程序,例如程序定义的错误。
发生异常时可以抛出异常。术语“异常”表示当前的程序执行停止,并且被重定向到最近的适用的catch子句。如果没有适用的catch子句存在,则程序的执行结束。
JDBC异常处理与Java异常处理非常相似,但对于JDBC,要处理的最常见异常是java.sql.SQLException。
SQLException方法
驱动程序和数据库中都会发生SQLException。 发生这种异常时,SQLException类型的对象将被传递给catch子句。
传递的SQLException对象具有以下可用于检索有关异常信息的方法 -
| 方法 | 描述 |
|---|---|
getErrorCode( ) |
获取与异常关联的错误代码。 |
getMessage( ) |
获取驱动程序处理的错误的JDBC驱动程序的错误消息,或获取数据库错误的Oracle错误代码和消息。 |
getSQLState( ) |
获取XOPEN SQLstate字符串。 对于JDBC驱动程序错误,不会从此方法返回有用的信息。 对于数据库错误,返回五位数的XOPEN SQLstate代码。 此方法可以返回null。 |
getNextException( ) |
获取异常链中的下一个Exception对象。 |
printStackTrace( ) |
打印当前异常或可抛出的异常,并将其追溯到标准错误流。 |
printStackTrace(PrintStream s) |
将此throwable及其回溯打印到指定的打印流。 |
printStackTrace(PrintWriter w) |
打印这个throwable,它是回溯到指定的打印器(PrintWriter)。 |
通过利用Exception对象提供的信息,可以捕获异常并适当地继续执行程序。下面是一个try块的一般形式 -
try {
// Your risky code goes between these curly braces!!!
}
catch(Exception ex) {
// Your exception handling code goes between these
// curly braces, similar to the exception clause
// in a PL/SQL block.
}
finally {
// Your must-always-be-executed code goes between these
// curly braces. Like closing database connection.
}
实例
学习研究以下示例代码以了解try …. catch … finally块的用法。将下面代码保存到文件:TryCatchFinally.java 中,
//STEP 1. Import required packages
// See more detail at http://www.yiibai.com/jdbc/
import java.sql.*;
public class TryCatchFinally {
// JDBC driver name and database URL
static final String JDBC_DRIVER = "com.mysql.jdbc.Driver";
static final String DB_URL = "jdbc:mysql://localhost/EMP";
// Database credentials
static final String USER = "root";
static final String PASS = "123456";
public static void main(String[] args) {
Connection conn = null;
try{
//STEP 2: Register JDBC driver
Class.forName("com.mysql.jdbc.Driver");
//STEP 3: Open a connection
System.out.println("Connecting to database...");
conn = DriverManager.getConnection(DB_URL,USER,PASS);
//STEP 4: Execute a query
System.out.println("Creating statement...");
Statement stmt = conn.createStatement();
String sql;
sql = "SELECT id, first, last, age FROM Employees";
ResultSet rs = stmt.executeQuery(sql);
//STEP 5: Extract data from result set
while(rs.next()){
//Retrieve by column name
int id = rs.getInt("id");
int age = rs.getInt("age");
String first = rs.getString("first");
String last = rs.getString("last");
//Display values
System.out.print("ID: " + id);
System.out.print(", Age: " + age);
System.out.print(", First: " + first);
System.out.println(", Last: " + last);
}
//STEP 6: Clean-up environment
rs.close();
stmt.close();
conn.close();
}catch(SQLException se){
//Handle errors for JDBC
se.printStackTrace();
}catch(Exception e){
//Handle errors for Class.forName
e.printStackTrace();
}finally{
//finally block used to close resources
try{
if(conn!=null)
conn.close();
}catch(SQLException se){
se.printStackTrace();
}//end finally try
}//end try
System.out.println("Goodbye!");
}//end main
}//end JDBCExample
现在编译上面例子中代码如下 -
F:\worksp\jdbc>javac -Djava.ext.dirs=F:\worksp\jdbc\libs TryCatchFinally.java
执行上面编译后的代码,得到以下结果 -
F:\worksp\jdbc>java -Djava.ext.dirs=F:\worksp\jdbc\libs TryCatchFinally
Connecting to database...
Thu Jun 01 02:59:01 CST 2017 WARN: Establishing SSL connection without server's identity verification is not recommended. According to MySQL 5.5.45+, 5.6.26+ and 5.7.6+ requirements SSL connection must be established by default if explicit option isn't set. For compliance with existing applications not using SSL the verifyServerCertificate property is set to 'false'. You need either to explicitly disable SSL by setting useSSL=false, or set useSSL=true and provide truststore for server certificate verification.
Creating statement...
ID: 100, Age: 28, First: Max, Last: Su
ID: 101, Age: 25, First: Wei, Last: Wang
ID: 102, Age: 35, First: Xueyou, Last: Zhang
ID: 103, Age: 30, First: Jack, Last: Ma
ID: 106, Age: 28, First: Curry, Last: Stephen
ID: 107, Age: 32, First: Kobe, Last: Bryant
Goodbye!
F:\worksp\jdbc>
JDBC异常的更多相关文章
- JDBC 异常特殊原因 (数据库只读解决办法)
JDBC 异常特殊原因 有时候并不是因为程序写的有问题 ,是因为 数据库只读 在sqlserver2005中附加数据库时,附加的数据库会变成只读的,只能进行查询操作. 解决方法: 1 打开Sq ...
- JDBC异常之数据库表不存在
JDBC异常之数据库表不存在 1.具体错误如下: com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException:Table 'YHD.t_yhd_ ...
- JDBC 异常简介 jDBC简介(六)
SQL 异常简介 对于数据库的操作访问,必然也很可能抛出异常. JDBC中定义了SQLException,用于描述数据库相关操作中可能出现的异常情况. java.sql.SQLException ...
- Spring之 JDBC 异常
JDBC异常抽象 Spring会将数据操作的异常转换为DataAccessException 解析错误码 SQLErrorCodeSQLExceptionTranslator ErrorCode定义 ...
- JDBC异常总结
1.异常一 (1)详情如下 com.mysql.jdbc.exceptions.jdbc4.MySQLNonTransientConnectionException: Data source reje ...
- 从源码解析 Spring JDBC 异常抽象
初入学习 JDBC 操作数据库,想必大家都写过下面的代码: 数据库为:H2 如果需要处理特定 SQL 异常,比如 SQL 语句错误,这个时候我们应该怎么办? 查看 SQLException 源码,我们 ...
- hive JDBC异常到多租户
hive jdbc执行select count(*) from test报错. return code 1 from org.apache.hadoop.hive.ql.exec.mr.MapRedT ...
- 使用JdbcTemplate简化JDBC操作 实现数据库操作
使用Spring JDBC框架方遍简单的完成JDBC操作,满足性能的需求且灵活性高. Spring JDBC框架由4个部分组成,即core.datasource.object.support. org ...
- SPRING IN ACTION 第4版笔记-第十章Hitting the database with spring and jdbc-001-Spring对原始JDBC的封装
1.spring扩展的jdbc异常 2.Template的运行机制 Spring separates the fixed and variable parts of the data-access p ...
随机推荐
- 15个Spring的核心注释示例
众所周知,Spring DI和Spring IOC是Spring Framework的核心概念.让我们从org.springframework.beans.factory.annotation和org ...
- input type= file 如何更改自定义的样式
input { @include wh(24px,22px);//sass 宽高 @include pa(0,0); //绝对定位 top:0:left:0: opacity: 0; //透明度: o ...
- 让浏览器兼容H5元素和媒体查询的代码
<!--[if lt IE 9]> <script src="https://oss.maxcdn.com/libs/html5shiv/3.7.0/html5shiv.j ...
- Java类的成员初始化顺序
Java类的成员初始化顺序 2017-06-01 代码: public class InitializeSequence { public static void main(String[] args ...
- 如何在线程中获取spring 管理的bean
转载自:https://my.oschina.net/skyline520/blog/181158?fromerr=GjtR6Wec spring xml中定义 <!--spring 工具类-- ...
- 园子里的一个Dal类
public class DALHelper { public static List<T> Search<T>() where T : SH_SetBase { using ...
- mongo源码学习(二)db.cpp之mongoDbMain方法分析
mongo后台进程的入口:mongo/src/mongo/db/dbmain.cpp,wmain(for windows)和main函数,main函数也很简单,就是委托给db.cpp中的mongoDb ...
- [mqtt]mqtt嵌入式移植
github eclipse paho source code: https://github.com/mqtt/mqtt.github.io/wiki/libraries STM32 mqtt移植: ...
- SD卡镜像烧写--树莓派为例
SD烧写镜像都要先擦除SD卡内容,然后用image烧写工具烧写镜像. SD卡标准官网:www.sdcard.org,提供标准的擦除工具sdformatter. windows下镜像烧写工具可选用Win ...
- 基于机器学习人脸识别face recognition具体的算法和原理
引自:http://blog.csdn.net/eclipsesy/article/details/78388468?utm_source=debugrun&utm_medium=referr ...