SQLException information
In this chapter you will learn:
- Extracting Information from SQLException
- Get the Details of a SQLException
- Print the stack trace for a SQLException to STDERR
Information from SQLException
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.sql.Statement;
//from j av a 2s.c om
public class Main {
public static void main(String[] args) throws Exception {
try {
Connection conn = getHSQLConnection();
conn.setAutoCommit(false);
Statement st = conn.createStatement();
st.executeUpdate("create table survey (id int,name varchar(30));");
st.executeUpdate("insert into survey (id,name ) values (1,'nameValue')");
st = conn.createStatement();
ResultSet rs = st.executeQuery("SELECT * FROM survey");
rs.close();
st.close();
conn.close();
} catch (SQLException sqle) {
String sqlMessage = sqle.getMessage();
String sqlState = sqle.getSQLState();
int vendorCode = sqle.getErrorCode();
System.err.println("Exception occurred:");
System.err.println("Message: " + sqlMessage);
System.err.println("SQL state: " + sqlState);
System.err.println("Vendor code: " + vendorCode + "\n----------------");
}
}
private static Connection getHSQLConnection() throws Exception {
Class.forName("org.hsqldb.jdbcDriver");
String url = "jdbc:hsqldb:mem:data/tutorial";
return DriverManager.getConnection(url, "sa", "");
}
}
Get the Details of a SQLException
} catch (SQLException e) {
while (e != null) {
String errorMessage = e.getMessage();//from j av a2s .c o m
System.err.println("sql error message:" + errorMessage);
// This vendor-independent string contains a code.
String sqlState = e.getSQLState();
System.err.println("sql state:" + sqlState);
int errorCode = e.getErrorCode();
System.err.println("error code:" + errorCode);
// String driverName = conn.getMetaData().getDriverName();
// System.err.println("driver name:"+driverName);
// processDetailError(drivername, errorCode);
e = e.getNextException();
}
Print the stack trace for a SQLException to STDERR
import java.io.PrintWriter;
import java.sql.SQLException;
public class Main {
//from j a v a2 s . c om
public static void printStackTrace(SQLException e) {
printStackTrace(e, new PrintWriter(System.err));
}
public static void printStackTrace(SQLException e, PrintWriter pw) {
SQLException next = e;
while (next != null) {
next.printStackTrace(pw);
next = next.getNextException();
if (next != null) {
pw.println("Next SQLException:");
}
}
}
}
Next chapter...
What you will learn in the next chapter:
Home » Java Tutorial » Statements, ResultSet, Exception, Warning