Connection Warning
In this chapter you will learn:
- Find out Warning message for Connection
- Check for a warning using a Connection object
- Print warning message from connection
SQL warning from Connection
You can check for a warning in three places:
- The Connection object (java.sql.Connection)
- The Statement object (java.sql.Statement)
- The ResultSet object (java.sql.ResultSet)
Connection for SQLWarning
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.SQLWarning;
//j a v a 2s. c o m
public class Main {
public static void main(String[] args) throws Exception {
try {
Connection conn = getConnection(); // get a java.sql.Connection object
SQLWarning warning = conn.getWarnings();
while (warning != null) {
// process connection warning
String message = warning.getMessage();
String sqlState = warning.getSQLState();
int errorCode = warning.getErrorCode();
warning = warning.getNextWarning();
}
}
catch (SQLException e) {
// ignore the exception
}
finally {
// close JDBC resources: ResultSet, Statement, Connection
}
}
}
Print warning message from connection
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.SQLException;
// j a v a 2 s.co m
public class Main {
public static void printWarnings(Connection conn) {
printWarnings(conn, new PrintWriter(System.err));
}
public static void printWarnings(Connection conn, PrintWriter pw) {
if (conn != null) {
try {
printStackTrace(conn.getWarnings(), pw);
} catch (SQLException e) {
printStackTrace(e, pw);
}
}
}
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