List of usage examples for java.sql SQLWarning getNextWarning
public SQLWarning getNextWarning()
SQLWarning
object by setNextWarning
. From source file:Main.java
public static void main(String[] argv) throws Exception { String driverName = "com.jnetdirect.jsql.JSQLDriver"; Class.forName(driverName);/*from w ww . j a v a 2s.c om*/ 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:Main.java
public static void main(String[] args) throws Exception { try {/*from w w w. ja va 2s.co m*/ 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 { Connection conn = getConnection(); conn.setAutoCommit(false);/* w w w. j a va2 s . co m*/ Statement st = conn.createStatement(); st.executeUpdate("create table survey (id int, name VARCHAR(30) );"); String INSERT_RECORD = "insert into survey(id, name) values(?,?)"; PreparedStatement pstmt = conn.prepareStatement(INSERT_RECORD); pstmt.setInt(1, 1); pstmt.setString(2, "name"); pstmt.executeUpdate(); // Get warnings on PreparedStatement object SQLWarning warning = pstmt.getWarnings(); while (warning != null) { // Process statement warnings... String message = warning.getMessage(); String sqlState = warning.getSQLState(); int errorCode = warning.getErrorCode(); warning = warning.getNextWarning(); } ResultSet rs = st.executeQuery("SELECT * FROM survey"); outputResultSet(rs); rs.close(); st.close(); conn.close(); }
From source file:Main.java
public static void main(String[] args) throws Exception { String dbURL = "jdbc:odbc:Companies"; try {/*from w ww .j a va2 s.c o m*/ // 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:ExecuteSQL.java
public static void main(String[] args) { Connection conn = null; // Our JDBC connection to the database server try {//from w w w. j av a 2 s .co 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:Connect.java
public static void main(String[] av) { String dbURL = "jdbc:odbc:Companies"; try {//from ww w .ja v a 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:Main.java
public static void displayError(SQLWarning warning) { while (warning != null) { if (warning instanceof DataTruncation) { displayError((DataTruncation) warning); } else {//from w ww . jav a2 s .com System.out.println(" Warning: " + warning.getMessage()); } warning = warning.getNextWarning(); } }
From source file:Main.java
static boolean checkForWarning(SQLWarning w) { if (w == null) { return false; }//w w w. j a v a2 s. c o m do { System.err.println("Warning:\nMessage: " + w.getMessage()); System.err.println("SQL state: " + w.getSQLState()); System.err.println("Vendor code: " + w.getErrorCode() + "\n----------------"); } while ((w = w.getNextWarning()) != null); return true; }
From source file:io.cloudslang.content.database.services.SQLCommandService.java
public static String executeSqlCommand(final SQLInputs sqlInputs) throws Exception { final ConnectionService connectionService = new ConnectionService(); try (final Connection connection = connectionService.setUpConnection(sqlInputs)) { connection.setReadOnly(false);/*from w ww . ja v a 2 s . c o m*/ final String dbType = sqlInputs.getDbType(); if (ORACLE_DB_TYPE.equalsIgnoreCase(dbType) && sqlInputs.getSqlCommand().toLowerCase().contains(DBMS_OUTPUT)) { final PreparedStatement preparedStatement = connection.prepareStatement(sqlInputs.getSqlCommand()); preparedStatement.setQueryTimeout(sqlInputs.getTimeout()); OracleDbmsOutput oracleDbmsOutput = new OracleDbmsOutput(connection); preparedStatement.executeQuery(); sqlInputs.setIUpdateCount(preparedStatement.getUpdateCount()); preparedStatement.close(); final String output = oracleDbmsOutput.getOutput(); oracleDbmsOutput.close(); return output; } else { final Statement statement = connection.createStatement(sqlInputs.getResultSetType(), sqlInputs.getResultSetConcurrency()); statement.setQueryTimeout(sqlInputs.getTimeout()); try { statement.execute(sqlInputs.getSqlCommand()); } catch (SQLException e) { if (SYBASE_DB_TYPE.equalsIgnoreCase(dbType)) { //during a dump sybase sends back status as exceptions. if (sqlInputs.getSqlCommand().trim().toLowerCase().startsWith("dump")) { return SQLUtils.processDumpException(e); } else if (sqlInputs.getSqlCommand().trim().toLowerCase().startsWith("load")) { return SQLUtils.processLoadException(e); } } else { throw e; } } ResultSet rs = statement.getResultSet(); if (rs != null) { ResultSetMetaData rsMtd = rs.getMetaData(); if (rsMtd != null) { sqlInputs.getLRows().clear(); int colCount = rsMtd.getColumnCount(); if (sqlInputs.getSqlCommand().trim().toLowerCase().startsWith("dbcc")) { while (rs.next()) { if (colCount >= 4) { sqlInputs.getLRows().add(rs.getString(4)); } } } else { String delimiter = (StringUtils.isNoneEmpty(sqlInputs.getStrDelim())) ? sqlInputs.getStrDelim() : ","; String strRowHolder; while (rs.next()) { strRowHolder = ""; for (int i = 1; i <= colCount; i++) { if (i > 1) { strRowHolder += delimiter; } strRowHolder += rs.getString(i); } sqlInputs.getLRows().add(strRowHolder); } } rs.close(); } } //For sybase, when dbcc command is executed, the result is shown in warning message else if (dbType.equalsIgnoreCase(SYBASE_DB_TYPE) && sqlInputs.getSqlCommand().trim().toLowerCase().startsWith("dbcc")) { SQLWarning warning = statement.getWarnings(); while (warning != null) { sqlInputs.getLRows().add(warning.getMessage()); warning = warning.getNextWarning(); } } sqlInputs.setIUpdateCount(statement.getUpdateCount()); } } return "Command completed successfully"; }
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;/*from w w w. j av a 2s. c om*/ } 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); } } } }