Example usage for java.sql Connection getWarnings

List of usage examples for java.sql Connection getWarnings

Introduction

In this page you can find the example usage for java.sql Connection getWarnings.

Prototype

SQLWarning getWarnings() throws SQLException;

Source Link

Document

Retrieves the first warning reported by calls on this Connection object.

Usage

From source file:Main.java

public static void main(String[] args) throws Exception {

    try {/*from w w w  . ja  v a2 s  . c om*/
        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
    }

}

From source file:Main.java

public static void main(String[] args) throws Exception {
    String dbURL = "jdbc:odbc:Companies";
    try {/*from w  w  w .  ja  va  2s  . c  om*/
        // Load the jdbc-odbc bridge driver
        Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
        // Enable logging
        DriverManager.setLogWriter(new PrintWriter((System.err)));

        System.out.println("Getting Connection");
        Connection conn = DriverManager.getConnection(dbURL, "user", "password");

        SQLWarning warn = conn.getWarnings();
        while (warn != null) {
            System.out.println("SQLState: " + warn.getSQLState());
            System.out.println("Message:  " + warn.getMessage());
            System.out.println("Vendor:   " + warn.getErrorCode());
            System.out.println("");
            warn = warn.getNextWarning();
        }

        conn.close();
    } catch (ClassNotFoundException e) {
        System.out.println("Can't load driver " + e);
    } catch (SQLException e) {
        System.out.println("Database access failed " + e);
    }
}

From source file:Main.java

public static void main(String[] argv) throws Exception {

    String driverName = "com.jnetdirect.jsql.JSQLDriver";
    Class.forName(driverName);/* w  w  w  . j  a  v  a  2s .  c  o  m*/

    String serverName = "127.0.0.1";
    String portNumber = "1433";
    String mydatabase = serverName + ":" + portNumber;
    String url = "jdbc:JSQLConnect://" + mydatabase;
    String username = "username";
    String password = "password";

    Connection connection = DriverManager.getConnection(url, username, password);

    try {
        SQLWarning warning = connection.getWarnings();
        while (warning != null) {
            String message = warning.getMessage();
            String sqlState = warning.getSQLState();
            int errorCode = warning.getErrorCode();
            warning = warning.getNextWarning();
        }
        Statement stmt = connection.createStatement();
        warning = stmt.getWarnings();
        if (warning != null) {

        }
        ResultSet resultSet = stmt.executeQuery("SELECT * FROM my_table");
        while (resultSet.next()) {
            warning = resultSet.getWarnings();
            if (warning != null) {
            }
        }
    } catch (SQLException e) {
    }

}

From source file:JDBCQuery.java

public static void main(String[] av) {
    try {/*w  w w  .java 2  s .  c  o  m*/
        System.out.println("Loading Driver (with Class.forName)");
        // Load the jdbc-odbc bridge driver
        Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");

        // Enable logging
        // DriverManager.setLogStream(System.err);

        System.out.println("Getting Connection");
        Connection conn = DriverManager.getConnection("jdbc:odbc:Companies", "ian", ""); // user, passwd

        // Any warnings generated by the connect?
        checkForWarning(conn.getWarnings());

        System.out.println("Creating Statement");
        Statement stmt = conn.createStatement();

        System.out.println("Executing Query");
        ResultSet rs = stmt.executeQuery("SELECT * FROM Companies");

        System.out.println("Retrieving Results");
        int i = 0;
        while (rs.next()) {

            System.out.println("Retrieving Company ID");
            int x = rs.getInt("CustNO");
            System.out.println("Retrieving Name");
            String s = rs.getString("Company");

            System.out.println("ROW " + ++i + ": " + x + "; " + s + "; " + ".");

        }

        rs.close(); // All done with that resultset
        stmt.close(); // All done with that statement
        conn.close(); // All done with that DB connection

    } catch (ClassNotFoundException e) {
        System.out.println("Can't load driver " + e);
    } catch (SQLException e) {
        System.out.println("Database access failed " + e);
    }
}

From source file:Connect.java

public static void main(String[] av) {
    String dbURL = "jdbc:odbc:Companies";
    try {//from  w  ww  .java  2  s.  c  om
        // Load the jdbc-odbc bridge driver
        Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");

        // Enable logging
        DriverManager.setLogWriter(new PrintWriter((System.err)));

        System.out.println("Getting Connection");
        Connection conn = DriverManager.getConnection(dbURL, "ian", ""); // user,
        // passwd

        // If a SQLWarning object is available, print its
        // warning(s). There may be multiple warnings chained.

        SQLWarning warn = conn.getWarnings();
        while (warn != null) {
            System.out.println("SQLState: " + warn.getSQLState());
            System.out.println("Message:  " + warn.getMessage());
            System.out.println("Vendor:   " + warn.getErrorCode());
            System.out.println("");
            warn = warn.getNextWarning();
        }

        // Do something with the connection here...

        conn.close(); // All done with that DB connection

    } catch (ClassNotFoundException e) {
        System.out.println("Can't load driver " + e);
    } catch (SQLException e) {
        System.out.println("Database access failed " + e);
    }
}

From source file:ExecuteSQL.java

public static void main(String[] args) {
    Connection conn = null; // Our JDBC connection to the database server
    try {/*from  w  w w.  j  a  v a  2s . c o  m*/
        String driver = null, url = null, user = "", password = "";

        // Parse all the command-line arguments
        for (int n = 0; n < args.length; n++) {
            if (args[n].equals("-d"))
                driver = args[++n];
            else if (args[n].equals("-u"))
                user = args[++n];
            else if (args[n].equals("-p"))
                password = args[++n];
            else if (url == null)
                url = args[n];
            else
                throw new IllegalArgumentException("Unknown argument.");
        }

        // The only required argument is the database URL.
        if (url == null)
            throw new IllegalArgumentException("No database specified");

        // If the user specified the classname for the DB driver, load
        // that class dynamically. This gives the driver the opportunity
        // to register itself with the DriverManager.
        if (driver != null)
            Class.forName(driver);

        // Now open a connection the specified database, using the
        // user-specified username and password, if any. The driver
        // manager will try all of the DB drivers it knows about to try to
        // parse the URL and connect to the DB server.
        conn = DriverManager.getConnection(url, user, password);

        // Now create the statement object we'll use to talk to the DB
        Statement s = conn.createStatement();

        // Get a stream to read from the console
        BufferedReader in = new BufferedReader(new InputStreamReader(System.in));

        // Loop forever, reading the user's queries and executing them
        while (true) {
            System.out.print("sql> "); // prompt the user
            System.out.flush(); // make the prompt appear now.
            String sql = in.readLine(); // get a line of input from user

            // Quit when the user types "quit".
            if ((sql == null) || sql.equals("quit"))
                break;

            // Ignore blank lines
            if (sql.length() == 0)
                continue;

            // Now, execute the user's line of SQL and display results.
            try {
                // We don't know if this is a query or some kind of
                // update, so we use execute() instead of executeQuery()
                // or executeUpdate() If the return value is true, it was
                // a query, else an update.
                boolean status = s.execute(sql);

                // Some complex SQL queries can return more than one set
                // of results, so loop until there are no more results
                do {
                    if (status) { // it was a query and returns a ResultSet
                        ResultSet rs = s.getResultSet(); // Get results
                        printResultsTable(rs, System.out); // Display them
                    } else {
                        // If the SQL command that was executed was some
                        // kind of update rather than a query, then it
                        // doesn't return a ResultSet. Instead, we just
                        // print the number of rows that were affected.
                        int numUpdates = s.getUpdateCount();
                        System.out.println("Ok. " + numUpdates + " rows affected.");
                    }

                    // Now go see if there are even more results, and
                    // continue the results display loop if there are.
                    status = s.getMoreResults();
                } while (status || s.getUpdateCount() != -1);
            }
            // If a SQLException is thrown, display an error message.
            // Note that SQLExceptions can have a general message and a
            // DB-specific message returned by getSQLState()
            catch (SQLException e) {
                System.err.println("SQLException: " + e.getMessage() + ":" + e.getSQLState());
            }
            // Each time through this loop, check to see if there were any
            // warnings. Note that there can be a whole chain of warnings.
            finally { // print out any warnings that occurred
                SQLWarning w;
                for (w = conn.getWarnings(); w != null; w = w.getNextWarning())
                    System.err.println("WARNING: " + w.getMessage() + ":" + w.getSQLState());
            }
        }
    }
    // Handle exceptions that occur during argument parsing, database
    // connection setup, etc. For SQLExceptions, print the details.
    catch (Exception e) {
        System.err.println(e);
        if (e instanceof SQLException)
            System.err.println("SQL State: " + ((SQLException) e).getSQLState());
        System.err.println(
                "Usage: java ExecuteSQL [-d <driver>] " + "[-u <user>] [-p <password>] <database URL>");
    }

    // Be sure to always close the database connection when we exit,
    // whether we exit because the user types 'quit' or because of an
    // exception thrown while setting things up. Closing this connection
    // also implicitly closes any open statements and result sets
    // associated with it.
    finally {
        try {
            conn.close();
        } catch (Exception e) {
        }
    }
}

From source file:Main.java

/**
 * Print warnings on a Connection to a specified PrintWriter. 
 *
 * @param conn Connection to print warnings from
 * @param pw PrintWriter to print to//from  w  w  w  .  j a v  a2 s  .co m
 */
public static void printWarnings(Connection conn, PrintWriter pw) {
    if (conn != null) {
        try {
            printStackTrace(conn.getWarnings(), pw);
        } catch (SQLException e) {
            printStackTrace(e, pw);
        }
    }
}

From source file:edu.lternet.pasta.doi.DOIScannerTest.java

private static Connection getConnection() throws Exception {
    Connection conn = null;
    SQLWarning warn;/*from  ww w . ja  va2 s.c  o m*/

    Class.forName(dbDriver);

    // Make the database connection
    conn = DriverManager.getConnection(dbUrl, dbUser, dbPassword);

    // If a SQLWarning object is available, print its warning(s).
    // There may be multiple warnings chained.
    warn = conn.getWarnings();

    if (warn != null) {
        while (warn != null) {
            System.err.println("SQLState: " + warn.getSQLState());
            System.err.println("Message:  " + warn.getMessage());
            System.err.println("Vendor: " + warn.getErrorCode());
            warn = warn.getNextWarning();
        }
    }

    return conn;

}

From source file:org.apache.airavata.registry.tool.DBMigrator.java

private static void executeSQL(String sql, Connection conn) throws Exception {
    if ("".equals(sql.trim())) {
        return;/* w w  w .j  a  v  a2 s . c  o  m*/
    }
    Statement statement = null;
    try {
        logger.debug("SQL : " + sql);

        boolean ret;
        int updateCount = 0, updateCountTotal = 0;
        statement = conn.createStatement();
        ret = statement.execute(sql);
        updateCount = statement.getUpdateCount();
        do {
            if (!ret) {
                if (updateCount != -1) {
                    updateCountTotal += updateCount;
                }
            }
            ret = statement.getMoreResults();
            if (ret) {
                updateCount = statement.getUpdateCount();
            }
        } while (ret);

        logger.debug(sql + " : " + updateCountTotal + " rows affected");

        SQLWarning warning = conn.getWarnings();
        while (warning != null) {
            logger.warn(warning + " sql warning");
            warning = warning.getNextWarning();
        }
        conn.clearWarnings();
    } catch (SQLException e) {
        if (e.getSQLState().equals("X0Y32")) {
            logger.info("Table Already Exists", e);
        } else {
            throw new Exception("Error occurred while executing : " + sql, e);
        }
    } finally {
        if (statement != null) {
            try {
                statement.close();
            } catch (SQLException e) {
                logger.error("Error occurred while closing result set.", e);
            }
        }
    }
}

From source file:org.wso2.mobile.utils.persistence.EMMDBInitializer.java

/**
 * executes given sql//from w ww .ja  v  a 2s  .  co m
 *
 * @param sql
 * @throws Exception
 */
private void executeSQL(String sql) throws Exception {
    // Check and ignore empty statements
    if ("".equals(sql.trim())) {
        return;
    }

    ResultSet resultSet = null;
    try {
        if (log.isDebugEnabled()) {
            log.debug("SQL : " + sql);
        }

        boolean ret;
        int updateCount, updateCountTotal = 0;
        ret = statement.execute(sql);
        updateCount = statement.getUpdateCount();
        resultSet = statement.getResultSet();
        do {
            if (!ret) {
                if (updateCount != -1) {
                    updateCountTotal += updateCount;
                }
            }
            ret = statement.getMoreResults();
            if (ret) {
                updateCount = statement.getUpdateCount();
                resultSet = statement.getResultSet();
            }
        } while (ret);

        if (log.isDebugEnabled()) {
            log.debug(sql + " : " + updateCountTotal + " rows affected");
        }
        Connection conn = dataSource.getConnection();
        SQLWarning warning = conn.getWarnings();
        while (warning != null) {
            log.debug(warning + " sql warning");
            warning = warning.getNextWarning();
        }
        conn.clearWarnings();
    } catch (SQLException e) {
        if (e.getSQLState().equals("X0Y32") || e.getSQLState().equals("42710")) {
            // eliminating the table already exception for the derby and DB2 database types
            if (log.isDebugEnabled()) {
                log.info("Table Already Exists. Hence, skipping table creation");
            }
        } else {
            throw new Exception("Error occurred while executing : " + sql, e);
        }
    } finally {
        if (resultSet != null) {
            try {
                resultSet.close();
            } catch (SQLException e) {
                log.error("Error occurred while closing result set.", e);
            }
        }
    }
}