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:com.idiro.utils.db.mysql.MySqlUtils.java

public static boolean createDatabase(JdbcDetails metastoreUrl, String database, String user,
        String user_password) {/*  www.  j av  a2s . c  o  m*/

    boolean ok = true;

    try {
        JdbcConnection conn = new JdbcConnection(metastoreUrl, new MySqlBasicStatement());
        conn.executeUpdate("CREATE DATABASE " + database);

        conn.executeUpdate("GRANT USAGE ON *.* TO '" + user + "'");
        conn.executeUpdate("SET PASSWORD FOR '" + user + "' = PASSWORD('" + user_password + "')");
        conn.executeUpdate("GRANT ALL PRIVILEGES ON " + database + ".* TO '" + user + "'");

        conn.executeUpdate("FLUSH PRIVILEGES");
    } catch (SQLException e) {
        logger.error("Error in the execution of an administration query");
        logger.error(e.getMessage());
        ok = false;
    } catch (Exception e) {
        logger.error("Cannot connect to the metastore " + metastoreUrl.getDburl());
        logger.error(e.getMessage());
        ok = false;
    }

    return ok;
}

From source file:org.guzz.web.context.spring.TransactionManagerUtils.java

/**
 * Apply the current transaction timeout, if any, to the given
 * Guzz Query object.// w w  w  .  ja v a2 s  .c o  m
 * @param query the Guzz Query object
 * @param transactionManager Guzz TransactionManager that the Query was created for
 * (may be <code>null</code>)
 * @see org.hibernate.Query#setTimeout
 */
public static void applyTransactionTimeout(PreparedStatement pstm, TransactionManager transactionManager) {
    Assert.notNull(pstm, "No PreparedStatement object specified");
    if (transactionManager != null) {
        WriteTranSessionHolder writeTranSessionHolder = (WriteTranSessionHolder) TransactionSynchronizationManager
                .getResource(transactionManager);

        if (writeTranSessionHolder != null && writeTranSessionHolder.hasTimeout()) {
            try {
                pstm.setQueryTimeout(writeTranSessionHolder.getTimeToLiveInSeconds());
            } catch (SQLException e) {
                throw new DataAccessResourceFailureException(e.getMessage(), e);
            }
        }
    }
}

From source file:TerminalMonitor.java

static public void showVersion(DatabaseMetaData meta) {
    try {//from   w ww.  j a  v a  2 s.  c o m
        System.out.println("TerminalMonitor v2.0");
        System.out.println("DBMS: " + meta.getDatabaseProductName() + " " + meta.getDatabaseProductVersion());
        System.out.println("JDBC Driver: " + meta.getDriverName() + " " + meta.getDriverVersion());
    } catch (SQLException e) {
        System.out.println("Failed to get version info: " + e.getMessage());
    }
}

From source file:cai.sql.SQL.java

public static void error_msg(String msg, SQLException e, String stm) throws RuntimeException {
    String s = new String(
            "SQL: " + msg + ": " + e.getErrorCode() + "/" + e.getSQLState() + " " + e.getMessage());

    if (stm != null)
        s += "\nSQL: Statement `" + stm + "'";

    logger.error(s);/*from   w  w  w.  j ava 2  s  .co m*/

    if (JDBC_abort_on_error)
        throw new RuntimeException(s);
}

From source file:Emporium.Controle.ContrVpne.java

public static ArrayList<Vpne> listaVpne(String where, String nomeBD, int idCli) {

    String sql = "SELECT * FROM vpne WHERE idCliente = " + idCli + " ";
    sql = sql + where + " ;";
    Connection conn = Conexao.conectar(nomeBD);
    ArrayList<Vpne> listaVpne = new ArrayList<Vpne>();

    try {//from  www . j av  a 2  s .c  om
        PreparedStatement valores = conn.prepareStatement(sql);
        valores.executeQuery();
        ResultSet result = (ResultSet) valores.executeQuery();

        while (result.next()) {

            int idCliente = result.getInt("idCliente");
            int idDepartamento = result.getInt("idDepartamento");
            String nomeDepto = result.getString("nomeDepartamento");

            String sro = result.getString("sro");
            String descricao = result.getString("descricao");
            String valor = result.getString("valor");

            String remetente = result.getString("remetente");
            String cnpj_remetente = result.getString("cnpj_remetente");
            String rlogradouro = result.getString("rlogradouro");
            String rnumero = result.getString("rnumero");
            String rbairro = result.getString("rbairro");
            String rcidade = result.getString("rcidade");
            String ruf = result.getString("ruf");

            String destinatario = result.getString("destinatario");
            String cpf_cnpj_dest = result.getString("cpf_cnpj_dest");
            String dlogradouro = result.getString("dlogradouro");
            String dnumero = result.getString("dnumero");
            String dbairro = result.getString("dbairro");
            String dcidade = result.getString("dcidade");
            String dcep = result.getString("dcep");
            String duf = result.getString("duf");

            String data = result.getString("data");

            Destinatario remVpne = new Destinatario(remetente, cnpj_remetente, rlogradouro, rnumero, rbairro,
                    rcidade, ruf);
            Destinatario destVpne = new Destinatario(destinatario, cpf_cnpj_dest, dlogradouro, dnumero, dbairro,
                    dcidade, dcep, duf);

            Vpne vp = new Vpne(sro, descricao, valor, idCliente, idDepartamento, nomeDepto, data, remVpne,
                    destVpne);
            listaVpne.add(vp);
        }
        valores.close();
        return listaVpne;
    } catch (SQLException e) {
        Logger.getLogger(ContrVpne.class.getName()).log(Level.WARNING, e.getMessage(), e);
        return listaVpne;
    } finally {
        Conexao.desconectar(conn);
    }
}

From source file:com.flexive.core.LifeCycleInfoImpl.java

/**
 * Update a tables LifeCycleInfo//from w  w w  . ja va2s  . c om
 *
 * @param table         table that contains the lifecycle
 * @param idField       field containing the id
 * @param id            the id to update
 * @param verField      field containing the id (optional)
 * @param ver           the version to update (optional)
 * @param updateCreated update created by/at as well?
 * @param throwOnNone   throw an exception if no rows were updated?
 * @throws FxUpdateException if a database field could not be updated
 */
public static void updateLifeCycleInfo(String table, String idField, String verField, long id, int ver,
        boolean updateCreated, boolean throwOnNone) throws FxUpdateException {
    final UserTicket ticket = FxContext.getUserTicket();

    Connection con = null;
    PreparedStatement stmt = null;

    try {
        con = Database.getDbConnection();
        stmt = con.prepareStatement("UPDATE " + table + " SET MODIFIED_BY=?, MODIFIED_AT=?"
                + (updateCreated ? ", CREATED_BY=?, CREATED_AT=?" : "") + " WHERE " + idField + "=?"
                + (verField != null && ver > 0 ? " AND " + verField + "=?" : ""));
        final long now = System.currentTimeMillis();
        stmt.setInt(1, (int) ticket.getUserId());
        stmt.setLong(2, now);
        if (updateCreated) {
            stmt.setInt(3, (int) ticket.getUserId());
            stmt.setLong(4, now);
            stmt.setLong(5, id);
        } else
            stmt.setLong(3, id);
        if (verField != null && ver > 0)
            stmt.setInt((updateCreated ? 6 : 4), ver);
        int iCnt = stmt.executeUpdate();
        if (iCnt != 1 && throwOnNone)
            throw new FxUpdateException("Updating LifeCycleInfo failed. " + iCnt + " rows were updated!");
    } catch (SQLException se) {
        throw new FxUpdateException(LOG, se.getMessage(), se);
    } finally {
        Database.closeObjects(LifeCycleInfoImpl.class, con, stmt);
    }
}

From source file:com.krawler.common.util.SchedulingUtilities.java

public static String getCmpHolidaydays(Connection conn, String companyId) throws ServiceException {
    String res = "";
    try {/*from   w w  w .jav  a2 s  .c  o  m*/
        String qry = "SELECT holiday, description FROM companyholidays WHERE companyid = ?";
        PreparedStatement pstmt = conn.prepareStatement(qry);
        pstmt.setString(1, companyId);
        ResultSet rs = pstmt.executeQuery();
        KWLJsonConverter j = new KWLJsonConverter();
        res = j.GetJsonForGrid(rs);
    } catch (SQLException e) {
        throw ServiceException.FAILURE("SchedulingUtilities.getCmpHolidaydays : " + e.getMessage(), e);
    }
    return res;
}

From source file:com.idiro.utils.db.mysql.MySqlUtils.java

public static boolean importTable(JdbcConnection conn, String tableName, Map<String, String> features,
        File fileIn, File tablePath, char delimiter, boolean header) {
    boolean ok = true;
    try {//  w w w. jav a 2s . c  om
        DbChecker dbCh = new DbChecker(conn);
        if (!dbCh.isTableExist(tableName)) {
            logger.debug("The table which has to be imported has not been created");
            logger.debug("Creation of the table");
            Integer ASCIIVal = (int) delimiter;
            String[] options = { ASCIIVal.toString(), tablePath.getCanonicalPath() };
            conn.executeQuery(new MySqlBasicStatement().createExternalTable(tableName, features, options));
        } else {
            //Check if it is the same table 
            if (!dbCh.areFeaturesTheSame(tableName, features.keySet())) {
                logger.warn("Mismatch between the table to import and the table in the database");
                return false;
            }

            logger.warn("Have to check if the table is external or not, I do not know how to do that");

        }
    } catch (SQLException e) {
        logger.debug("Fail to watch the datastore");
        logger.debug(e.getMessage());
        return false;
    } catch (IOException e) {
        logger.warn("Fail to get the output path from a File object");
        logger.warn(e.getMessage());
        return false;
    }

    //Check if the input file has the right number of field
    FileChecker fChIn = new FileChecker(fileIn);
    FileChecker fChOut = new FileChecker(tablePath);
    String strLine = "";
    try {

        if (fChIn.isDirectory() || !fChIn.canRead()) {
            logger.warn("The file " + fChIn.getFilename() + "is a directory or can not be read");
            return false;
        }
        BufferedReader br = new BufferedReader(new FileReader(fileIn));
        //Read first line
        strLine = br.readLine();
        br.close();
    } catch (IOException e1) {
        logger.debug("Fail to open the file" + fChIn.getFilename());
        return false;
    }

    if (StringUtils.countMatches(strLine, String.valueOf(delimiter)) != features.size() - 1) {
        logger.warn("File given does not match with the delimiter '" + delimiter
                + "' given and the number of fields '" + features.size() + "'");
        return false;
    }

    BufferedWriter bw = null;
    BufferedReader br = null;

    try {
        bw = new BufferedWriter(new FileWriter(tablePath));
        logger.debug("read the file" + fileIn.getAbsolutePath());
        br = new BufferedReader(new FileReader(fileIn));
        String delimiterStr = "" + delimiter;
        //Read File Line By Line
        while ((strLine = br.readLine()) != null) {
            bw.write("\"" + strLine.replace(delimiterStr, "\",\"") + "\"\n");
        }
        br.close();

        bw.close();
    } catch (FileNotFoundException e1) {
        logger.error(e1.getCause() + " " + e1.getMessage());
        logger.error("Fail to read " + fileIn.getAbsolutePath());
        ok = false;
    } catch (IOException e1) {
        logger.error("Error writting, reading on the filesystem from the directory" + fChIn.getFilename()
                + " to the file " + fChOut.getFilename());
        ok = false;
    }

    return ok;
}

From source file:gsn.http.ContainerInfoHandler.java

/**
 * returns null if there is an error./*from ww  w . j a  v  a  2 s  .co  m*/
 * only return the latest value, in case of non-unique time-stamps, the primary key is used.
 * @param virtual_sensor_name
 * @return
 */
public static ArrayList<StreamElement> getMostRecentValueFor(String virtual_sensor_name) {
    //System.out.println("GET NEW FOR = "+virtual_sensor_name);
    StringBuilder query = new StringBuilder("select * from ").append(virtual_sensor_name)
            .append(" where timed = (select max(timed) from ").append(virtual_sensor_name)
            .append(") order by pk desc limit 1");
    ArrayList<StreamElement> toReturn = new ArrayList<StreamElement>();
    try {
        DataEnumerator result = Main.getStorage(virtual_sensor_name).executeQuery(query, true);
        while (result.hasMoreElements())
            toReturn.add(result.nextElement());
    } catch (SQLException e) {
        logger.error("ERROR IN EXECUTING, query: " + query + ": " + e.getMessage());
        return null;
    }
    return toReturn;
}

From source file:org.mitre.jdbc.datasource.H2DataSourceFactory.java

protected static boolean testExecuteScriptQuery(Connection conn, String executeScriptQuery) {
    boolean result;
    try {//from   w  w w . j av a  2  s.co  m
        //If the ResultSet has any rows, the first method will return true
        result = !executeQuery(conn, executeScriptQuery).first();
    } catch (SQLException e) {
        //Only return true if the exception we got is that the table was not found
        result = e.getMessage().toLowerCase().matches("table \".*\" not found.*\n*.*");
    }
    logger.debug("Executed query " + executeScriptQuery + " with result " + result);

    return result;
}