JDBC 异常处理
2018-03-21 14:03 更新
JDBC教程 - JDBC异常处理
驱动程序或数据库中可能发生SQL异常。
例如,SQL语句中的语法错误将导致SQL异常。或者我们没有更新表的权限。
当发生这种异常时, SQLException 类型的对象将被传递给catch子句。
SQLException对象具有以下方法:
| 方法 | 描述 |
|---|---|
| getErrorCode() | 获取错误编号。 |
| getMessage() | 获取错误消息。 |
| getSQLState() | 获取SQLstate字符串。 对于数据库错误,将返回五位数的XOPEN SQLstate代码。 |
| getNextException() | 获取异常链中的下一个异常对象。 |
| printStackTrace() | 将当前异常及其回溯打印到标准错误流。 |
| printStackTrace(PrintStream s) | 将此可抛弃项及其回溯打印到指定的打印流。 |
| printStackTrace(PrintWriter w) | 将此可抛弃项及其回溯打印到指定的打印作者。 |
例子
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
public class Main {
// JDBC driver name and database URL
static final String JDBC_DRIVER = "org.hsqldb.jdbcDriver";
static final String DB_URL = "jdbc:hsqldb:mem:db_file";
// Database credentials
static final String USER = "sa";
static final String PASS = "";
public static void main(String[] args) {
Connection conn = null;
Statement stmt = null;
try {
// STEP 2: Register JDBC driver
Class.forName(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...");
stmt = conn.createStatement();
String sql;
sql = "SELECT id, first, last, age FROM Employees";
stmt.executeUpdate("CREATE TABLE Employees ( id INTEGER IDENTITY, first VARCHAR(256), last VARCHAR(256),age INTEGER)");
stmt.executeUpdate("INSERT INTO Employees VALUES(1,"Jack","Smith", 100)");
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");
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) {
se.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
} finally {
// finally block used to close resources
try {
if (stmt != null)
stmt.close();
} catch (SQLException se2) {
}
try {
if (conn != null)
conn.close();
} catch (SQLException se) {
se.printStackTrace();
}
}
System.out.println("Goodbye!");
}
}
以上内容是否对您有帮助:
← JDBC 事务

免费 AI IDE


更多建议: