Example usage for java.sql SQLException getMessage

List of usage examples for java.sql SQLException getMessage

Introduction

In this page you can find the example usage for java.sql SQLException getMessage.

Prototype

public String getMessage() 

Source Link

Document

Returns the detail message string of this throwable.

Usage

From source file:HelloMySQLJDBC.java

private void displaySQLErrors(SQLException e) {
    System.out.println("SQLException: " + e.getMessage());
    System.out.println("SQLState:     " + e.getSQLState());
    System.out.println("VendorError:  " + e.getErrorCode());
}

From source file:MainClass.java

public MainClass() {
    try {//from w w  w .ja  va 2  s .c o  m
        Class.forName("COM.cloudscape.core.RmiJdbcDriver");
        Connection connection = DriverManager.getConnection("jdbc:cloudscape:rmi:books");
        Statement statement = connection.createStatement();
        ResultSet resultSet = statement.executeQuery("SELECT * FROM authors");
        ResultSetMetaData metaData = resultSet.getMetaData();
        int numberOfColumns = metaData.getColumnCount();

        for (int i = 1; i <= numberOfColumns; i++) {
            System.out.println(metaData.getColumnName(i) + "\t");
        }

        while (resultSet.next()) {

            for (int i = 1; i <= numberOfColumns; i++) {
                System.out.println(resultSet.getObject(i) + "\t");
            }

            System.out.println("\n");
        }

        statement.close();
        connection.close();
    } catch (SQLException sqlException) {
        System.out.println(sqlException.getMessage());
    } catch (ClassNotFoundException classNotFound) {
        System.out.println("Driver Not Found");
        System.exit(1);
    }
}

From source file:com.neupane.springJDBC.controller.CustomerControler.java

@RequestMapping(method = RequestMethod.GET)
public ModelAndView index() throws ClassNotFoundException, SQLException {
    ModelAndView mv = new ModelAndView("index");
    try {//www .ja v a2  s .  c  om
        mv.addObject("customer", customerDAO.getAll());
    } catch (SQLException sql) {
        System.out.println(sql.getMessage());
    }
    return mv;
}

From source file:com.espertech.esper.epl.db.DatabasePollingViewableFactory.java

/**
 * Creates the viewable for polling via database SQL query.
 * @param streamNumber is the stream number of the view
 * @param databaseStreamSpec provides the SQL statement, database name and additional info
 * @param databaseConfigService for getting database connection and settings
 * @param eventAdapterService for generating event beans from database information
 * @param epStatementAgentInstanceHandle is the statements-own handle for use in registering callbacks with services
 * @param columnTypeConversionHook hook for statement-specific column conversion
 * @param outputRowConversionHook hook for statement-specific row conversion
 * @param enableJDBCLogging indicator to enable JDBC logging
 * @return viewable providing poll functionality
 * @throws ExprValidationException if the validation failed
 *//*from   w ww. ja  v a 2s.  co  m*/
public static HistoricalEventViewable createDBStatementView(String statementId, int streamNumber,
        DBStatementStreamSpec databaseStreamSpec, DatabaseConfigService databaseConfigService,
        EventAdapterService eventAdapterService, EPStatementAgentInstanceHandle epStatementAgentInstanceHandle,
        SQLColumnTypeConversion columnTypeConversionHook, SQLOutputRowConversion outputRowConversionHook,
        boolean enableJDBCLogging) throws ExprValidationException {
    // Parse the SQL for placeholders and text fragments
    List<PlaceholderParser.Fragment> sqlFragments;
    try {
        sqlFragments = PlaceholderParser.parsePlaceholder(databaseStreamSpec.getSqlWithSubsParams());
    } catch (PlaceholderParseException ex) {
        String text = "Error parsing SQL";
        throw new ExprValidationException(text + ", reason: " + ex.getMessage());
    }

    // Assemble a PreparedStatement and parameter list
    String preparedStatementText = createPreparedStatement(sqlFragments);
    SQLParameterDesc parameterDesc = getParameters(sqlFragments);
    if (log.isDebugEnabled()) {
        log.debug(".createDBEventStream preparedStatementText=" + preparedStatementText + " parameterDesc="
                + parameterDesc);
    }

    // Get a database connection
    String databaseName = databaseStreamSpec.getDatabaseName();
    DatabaseConnectionFactory databaseConnectionFactory;
    ColumnSettings metadataSetting;
    try {
        databaseConnectionFactory = databaseConfigService.getConnectionFactory(databaseName);
        metadataSetting = databaseConfigService.getQuerySetting(databaseName);
    } catch (DatabaseConfigException ex) {
        String text = "Error connecting to database '" + databaseName + '\'';
        log.error(text, ex);
        throw new ExprValidationException(text + ", reason: " + ex.getMessage());
    }

    Connection connection;
    try {
        connection = databaseConnectionFactory.getConnection();
    } catch (DatabaseConfigException ex) {
        String text = "Error connecting to database '" + databaseName + '\'';
        log.error(text, ex);
        throw new ExprValidationException(text + ", reason: " + ex.getMessage());
    }

    // On default setting, if we detect Oracle in the connection then don't query metadata from prepared statement
    ConfigurationDBRef.MetadataOriginEnum metaOriginPolicy = metadataSetting.getMetadataRetrievalEnum();
    if (metaOriginPolicy == ConfigurationDBRef.MetadataOriginEnum.DEFAULT) {
        String connectionClass = connection.getClass().getName();
        if ((connectionClass.toLowerCase().contains("oracle")
                || (connectionClass.toLowerCase().contains("timesten")))) {
            // switch to sample statement if we are dealing with an oracle connection
            metaOriginPolicy = ConfigurationDBRef.MetadataOriginEnum.SAMPLE;
        }
    }

    QueryMetaData queryMetaData;
    try {
        if ((metaOriginPolicy == ConfigurationDBRef.MetadataOriginEnum.METADATA)
                || (metaOriginPolicy == ConfigurationDBRef.MetadataOriginEnum.DEFAULT)) {
            queryMetaData = getPreparedStmtMetadata(connection, parameterDesc.getParameters(),
                    preparedStatementText, metadataSetting);
        } else {
            String sampleSQL;
            boolean isGivenMetadataSQL = true;
            if (databaseStreamSpec.getMetadataSQL() != null) {
                sampleSQL = databaseStreamSpec.getMetadataSQL();
                isGivenMetadataSQL = true;
                if (log.isInfoEnabled()) {
                    log.info(".createDBStatementView Using provided sample SQL '" + sampleSQL + "'");
                }
            } else {
                // Create the sample SQL by replacing placeholders with null and
                // SAMPLE_WHERECLAUSE_PLACEHOLDER with a "where 1=0" clause
                sampleSQL = createSamplePlaceholderStatement(sqlFragments);

                if (log.isInfoEnabled()) {
                    log.info(".createDBStatementView Using un-lexed sample SQL '" + sampleSQL + "'");
                }

                // If there is no SAMPLE_WHERECLAUSE_PLACEHOLDER, lexical analyse the SQL
                // adding a "where 1=0" clause.
                if (parameterDesc.getBuiltinIdentifiers().length != 1) {
                    sampleSQL = lexSampleSQL(sampleSQL);
                    if (log.isInfoEnabled()) {
                        log.info(".createDBStatementView Using lexed sample SQL '" + sampleSQL + "'");
                    }
                }
            }

            // finally get the metadata by firing the sample SQL
            queryMetaData = getExampleQueryMetaData(connection, parameterDesc.getParameters(), sampleSQL,
                    metadataSetting, isGivenMetadataSQL);
        }
    } catch (ExprValidationException ex) {
        try {
            connection.close();
        } catch (SQLException e) {
            // don't handle
        }
        throw ex;
    }

    // Close connection
    try {
        connection.close();
    } catch (SQLException e) {
        String text = "Error closing connection";
        log.error(text, e);
        throw new ExprValidationException(text + ", reason: " + e.getMessage());
    }

    // Create event type
    // Construct an event type from SQL query result metadata
    Map<String, Object> eventTypeFields = new HashMap<String, Object>();
    int columnNum = 1;
    for (Map.Entry<String, DBOutputTypeDesc> entry : queryMetaData.getOutputParameters().entrySet()) {
        String name = entry.getKey();
        DBOutputTypeDesc dbOutputDesc = entry.getValue();

        Class clazz;
        if (dbOutputDesc.getOptionalBinding() != null) {
            clazz = dbOutputDesc.getOptionalBinding().getType();
        } else {
            clazz = SQLTypeMapUtil.sqlTypeToClass(dbOutputDesc.getSqlType(), dbOutputDesc.getClassName());
        }

        if (columnTypeConversionHook != null) {

            Class newValue = columnTypeConversionHook.getColumnType(new SQLColumnTypeContext(
                    databaseStreamSpec.getDatabaseName(), databaseStreamSpec.getSqlWithSubsParams(), name,
                    clazz, dbOutputDesc.getSqlType(), columnNum));
            if (newValue != null) {
                clazz = newValue;
            }

        }
        eventTypeFields.put(name, clazz);
        columnNum++;
    }

    EventType eventType;
    if (outputRowConversionHook == null) {
        String outputEventType = statementId + "_dbpoll_" + streamNumber;
        eventType = eventAdapterService.createAnonymousMapType(outputEventType, eventTypeFields);
    } else {
        Class carrierClass = outputRowConversionHook
                .getOutputRowType(new SQLOutputRowTypeContext(databaseStreamSpec.getDatabaseName(),
                        databaseStreamSpec.getSqlWithSubsParams(), eventTypeFields));
        if (carrierClass == null) {
            throw new ExprValidationException("Output row conversion hook returned no type");
        }
        eventType = eventAdapterService.addBeanType(carrierClass.getName(), carrierClass, false, false, false);
    }

    // Get a proper connection and data cache
    ConnectionCache connectionCache;
    DataCache dataCache;
    try {
        connectionCache = databaseConfigService.getConnectionCache(databaseName, preparedStatementText);
        dataCache = databaseConfigService.getDataCache(databaseName, epStatementAgentInstanceHandle);
    } catch (DatabaseConfigException e) {
        String text = "Error obtaining cache configuration";
        log.error(text, e);
        throw new ExprValidationException(text + ", reason: " + e.getMessage());
    }

    PollExecStrategyDBQuery dbPollStrategy = new PollExecStrategyDBQuery(eventAdapterService, eventType,
            connectionCache, preparedStatementText, queryMetaData.getOutputParameters(),
            columnTypeConversionHook, outputRowConversionHook, enableJDBCLogging);

    return new DatabasePollingViewable(streamNumber, queryMetaData.getInputParameters(), dbPollStrategy,
            dataCache, eventType);
}

From source file:gestores.PoolDeConexiones.java

protected void pedirConexion() throws Exception {
    if (conexion == null) {
        try {/*from w w w .j a v  a2s. c o m*/
            BasicDataSource basicDataSource = new BasicDataSource();
            basicDataSource.setDriverClassName("com.mysql.jdbc.Driver");
            basicDataSource.setUrl("jdbc:mysql://localhost:3306/osg");
            basicDataSource.setUsername("root");
            basicDataSource.setPassword("root");
            basicDataSource.setMaxActive(20);
            basicDataSource.setMaxIdle(2);
            conexion = basicDataSource.getConnection();
            conexion.setAutoCommit(false);
        } catch (SQLException e) {
            throw new Exception(e.getMessage());
        }
    }
}

From source file:com.me.DAO.DAO1.java

public void close(Connection connection) {
    if (connection != null) {
        try {/*from  w w  w. j a  va  2 s  .  c o  m*/
            DbUtils.close(connection);
        } catch (SQLException ex) {
            System.out.println(ex.getMessage());
        }
    }
}

From source file:com.aurel.track.dbase.MigrateTo37.java

private static void addBaseLineChange(PreparedStatement pstmtBaseLineChange, Integer fieldChangeID,
        Integer transactionID, int fieldKey, Date newDate, Date oldDate) {
    try {// ww  w .j ava 2 s  . c  o m
        pstmtBaseLineChange.setInt(1, fieldChangeID);
        pstmtBaseLineChange.setInt(2, fieldKey);
        pstmtBaseLineChange.setInt(3, transactionID);
        if (newDate == null) {
            pstmtBaseLineChange.setDate(4, null);
        } else {
            pstmtBaseLineChange.setDate(4, new java.sql.Date(newDate.getTime()));
        }
        if (oldDate == null) {
            pstmtBaseLineChange.setDate(5, null);
        } else {
            pstmtBaseLineChange.setDate(5, new java.sql.Date(oldDate.getTime()));
        }
        pstmtBaseLineChange.setInt(6, ValueType.DATE);
        pstmtBaseLineChange.setString(7, UUID.randomUUID().toString());
        pstmtBaseLineChange.executeUpdate();
    } catch (SQLException e) {
        LOGGER.error("Adding a field change for base line with transactionID " + transactionID
                + " fieldChangeID " + fieldChangeID + " fieldKey " + fieldKey + " newDate " + newDate
                + " oldDate " + oldDate + " failed with " + e.getMessage(), e);
        System.err.println(ExceptionUtils.getStackTrace(e));
    }
}

From source file:cz.incad.Kramerius.security.userscommands.get.PublicUserActivation.java

@Override
public void doCommand() throws IOException {
    try {//from   w  w  w. j a v  a2 s  .  c om
        HttpServletRequest request = this.requestProvider.get();
        String keyParam = request.getParameter(KEY);
        User user = this.notActivatedUsersSingleton.getNotActivatedUser(keyParam);
        if (user != null) {
            this.userManager.activateUser(user);
        }
        String appContext = ApplicationURL.applicationContextPath(request);
        this.responseProvider.get().sendRedirect("/" + appContext + "/useractivated.jsp");
    } catch (SQLException e) {
        LOGGER.log(Level.SEVERE, e.getMessage(), e);
    }
}

From source file:com.cws.esolutions.security.dao.audit.impl.AuditDAOImplTest.java

@Test
public void getAuditInterval() {
    try {//from  w  ww.j  av  a 2  s.c o m
        Assert.assertNotNull(auditDAO.getAuditInterval("f42fb0ba-4d1e-1126-986f-800cd2650000", 1));
    } catch (SQLException sqx) {
        Assert.fail(sqx.getMessage());
    }
}

From source file:org.jfree.chart.demo.JDBCXYChartDemo.java

private XYDataset readData() {
    JDBCXYDataset jdbcxydataset = null;/*from  ww  w.  j a  v  a 2s  .  co  m*/
    String s = "jdbc:postgresql://nomad/jfreechartdb";
    try {
        Class.forName("org.postgresql.Driver");
    } catch (ClassNotFoundException classnotfoundexception) {
        System.err.print("ClassNotFoundException: ");
        System.err.println(classnotfoundexception.getMessage());
    }
    try {
        Connection connection = DriverManager.getConnection(s, "jfreechart", "password");
        jdbcxydataset = new JDBCXYDataset(connection);
        String s1 = "SELECT * FROM XYDATA1;";
        jdbcxydataset.executeQuery(s1);
        connection.close();
    } catch (SQLException sqlexception) {
        System.err.print("SQLException: ");
        System.err.println(sqlexception.getMessage());
    } catch (Exception exception) {
        System.err.print("Exception: ");
        System.err.println(exception.getMessage());
    }
    return jdbcxydataset;
}