驅(qū)動程序或數(shù)據(jù)庫中可能發(fā)生SQL異常。
例如,SQL語句中的語法錯誤將導(dǎo)致SQL異常?;蛘呶覀儧]有更新表的權(quán)限。
當(dāng)發(fā)生這種異常時(shí), SQLException
類型的對象將被傳遞給catch子句。
SQLException對象具有以下方法:
方法 | 描述 |
---|---|
getErrorCode() | 獲取錯誤編號。 |
getMessage() | 獲取錯誤消息。 |
getSQLState() | 獲取SQLstate字符串。 對于數(shù)據(jù)庫錯誤,將返回五位數(shù)的XOPEN SQLstate代碼。 |
getNextException() | 獲取異常鏈中的下一個(gè)異常對象。 |
printStackTrace() | 將當(dāng)前異常及其回溯打印到標(biāo)準(zhǔn)錯誤流。 |
printStackTrace(PrintStream s) | 將此可拋棄項(xiàng)及其回溯打印到指定的打印流。 |
printStackTrace(PrintWriter w) | 將此可拋棄項(xiàng)及其回溯打印到指定的打印作者。 |
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!"); } }
更多建議: