Example usage for java.sql SQLException printStackTrace

List of usage examples for java.sql SQLException printStackTrace

Introduction

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

Prototype

public void printStackTrace() 

Source Link

Document

Prints this throwable and its backtrace to the standard error stream.

Usage

From source file:jfutbol.com.jfutbol.GcmSender.java

public static void updateNotificationAsSent(int userId) {
    Connection conn = null;/*from   w  w  w. j av a  2 s  .co m*/
    Statement stmt = null;

    try {
        // STEP 2: Register JDBC driver
        Class.forName(JDBC_DRIVER);
        // STEP 3: Open a connection
        System.out.println("Connecting to database...");
        conn = DriverManager.getConnection(DB_URL, USER, PASS);
        // STEP 4: Execute a query
        System.out.println("Creating statement...");
        stmt = conn.createStatement();
        String sql;
        sql = "UPDATE notifications SET sentByGCM=1 WHERE userId=" + userId;
        int rs = stmt.executeUpdate(sql);
        // STEP 5: Extract data from result set
        if (rs > 0) {
            // System.out.print("Notifications sent to userId: "+userId);
        }
        // STEP 6: Clean-up environment
        stmt.close();
        conn.close();
    } catch (SQLException se) {
        // Handle errors for JDBC
        log.error(se.getMessage());
        se.printStackTrace();
    } catch (Exception e) {
        // Handle errors for Class.forName
        log.error(e.getMessage());
        e.printStackTrace();
    } finally {
        // finally block used to close resources
        try {
            if (stmt != null)
                stmt.close();
        } catch (SQLException se2) {
            log.error(se2.getMessage());
        } // nothing we can do
        try {
            if (conn != null)
                conn.close();
        } catch (SQLException se) {
            log.error(se.getMessage());
            se.printStackTrace();
        } // end finally try
    } // end try
}

From source file:com.cloudera.recordbreaker.analyzer.DataQuery.java

public synchronized static DataQuery getInstance(boolean force) {
    if (force && dataQuery != null) {
        try {//from   w  ww.j a va2s. co  m
            dataQuery.close();
        } catch (SQLException sqe) {
        }
        dataQuery = null;
    }
    if (force || (!inited)) {
        try {
            dataQuery = new DataQuery();
        } catch (SQLException se) {
            se.printStackTrace();
        } finally {
            inited = true;
        }
    }
    return dataQuery;
}

From source file:com.dynamobi.ws.util.DB.java

@SuppressWarnings(value = { "unchecked" })
public static <T extends DBLoader> void execute(String query, T obj, List<T> list) {
    Connection conn = null;//from  www  .j  av a  2 s .c o  m
    PreparedStatement ps = null;
    ResultSet rs = null;

    try {
        conn = getConnection();
        ps = conn.prepareStatement(query);
        ps.setMaxRows(0);
        if (ps.execute()) {
            rs = ps.getResultSet();
        }

        while (rs != null && rs.next()) {
            obj.loadRow(rs);
            if (list != null) {
                list.add((T) obj.copy());
            }
        }
        obj.finalize();
    } catch (SQLException ex) {
        obj.exception(ex);
    } catch (Exception ex) {
        ex.printStackTrace();
    } finally {
        if (conn != null) {
            releaseConnection();
        }
        try {
            if (ps != null) {
                ps.close();
            }
        } catch (SQLException ex1) {
            ex1.printStackTrace();
        }
        try {
            if (rs != null) {
                rs.close();
            }
        } catch (SQLException ex3) {
            ex3.printStackTrace();
        }
    }
}

From source file:com.magnet.mmx.server.plugin.mmxmgmt.apns.APNSPushMessageSenderTest.java

@AfterClass
public static void teardown() {
    try {/*from   w w  w.  j a va 2 s. c om*/
        ds.close();
    } catch (SQLException e) {
        e.printStackTrace();
    }
}

From source file:org.springside.modules.test.data.H2Fixtures.java

/**
 * ,excludeTables.disable.//from   w ww  . j a  v  a 2s .c o  m
 */
public static void deleteAllTable(DataSource dataSource, String... excludeTables) {

    List<String> tableNames = new ArrayList<String>();
    ResultSet rs = null;
    try {
        rs = dataSource.getConnection().getMetaData().getTables(null, null, null, new String[] { "TABLE" });
        while (rs.next()) {
            String tableName = rs.getString("TABLE_NAME");
            if (Arrays.binarySearch(excludeTables, tableName) < 0) {
                tableNames.add(tableName);
            }
        }

        deleteTable(dataSource, tableNames.toArray(new String[tableNames.size()]));
    } catch (SQLException e) {
        Exceptions.unchecked(e);
    } finally {
        if (rs != null) {
            try {
                rs.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }

}

From source file:agendavital.modelo.data.Noticia.java

public static TreeMap<LocalDate, ArrayList<Noticia>> buscar(String _parametro)
        throws ConexionBDIncorrecta, SQLException {
    final DateTimeFormatter dateFormatter = DateTimeFormatter.ofPattern("dd-MM-yyyy");
    ArrayList<String> _tags = UtilidadesBusqueda.separarPalabras(_parametro);
    TreeMap<LocalDate, ArrayList<Noticia>> busqueda = null;
    try (Connection conexion = ConfigBD.conectar()) {
        busqueda = new TreeMap<>();
        for (String _tag : _tags) {
            String tag = ConfigBD.String2Sql(_tag, true);
            String buscar = String.format("SELECT id_Noticia, fecha from noticias "
                    + "WHERE id_noticia IN (SELECT id_noticia from momentos_noticias_etiquetas "
                    + "WHERE id_etiqueta IN (SELECT id_etiqueta from etiquetas WHERE nombre LIKE %s)) "
                    + "OR titulo LIKE %s " + "OR cuerpo LIKE %s " + "OR categoria LIKE %s "
                    + "OR fecha LIKE %s; ", tag, tag, tag, tag, tag);
            ResultSet rs = conexion.createStatement().executeQuery(buscar);
            while (rs.next()) {
                LocalDate date = LocalDate.parse(rs.getString("fecha"), dateFormatter);
                Noticia insertarNoticia = new Noticia(rs.getInt("id_noticia"));
                if (busqueda.containsKey(date)) {
                    boolean encontrado = false;
                    for (int i = 0; i < busqueda.get(date).size() && !encontrado; i++)
                        if (busqueda.get(date).get(i).getId() == insertarNoticia.getId())
                            encontrado = true;
                    if (!encontrado)
                        busqueda.get(date).add(insertarNoticia);
                } else {
                    busqueda.put(date, new ArrayList<>());
                    busqueda.get(date).add(insertarNoticia);
                }/*from   w ww .  j  a  v a2s .com*/
            }

        }
    } catch (SQLException e) {
        e.printStackTrace();
    }
    Iterator it = busqueda.keySet().iterator();
    return busqueda;
}

From source file:com.splicemachine.tutorials.model.RULPredictiveModel.java

/**
 * Stored Procedure for Predictions//from w  ww .  j av  a  2 s . c  o  m
 */
public static void predictRUL(String sensorTableName, String resultsTableName, String savedModelPath,
        int loopinterval) {

    try {

        //Initialize variables
        if (sensorTableName == null || sensorTableName.length() == 0)
            sensorTableName = "IOT.SENSOR_AGG_1_VIEW";
        if (resultsTableName == null || resultsTableName.length() == 0)
            resultsTableName = "IOT.PREDICTION_EXT";
        if (savedModelPath == null || savedModelPath.length() == 0)
            savedModelPath = "/tmp";
        if (!savedModelPath.endsWith("/"))
            savedModelPath = savedModelPath + "/";
        savedModelPath += "model/";

        String jdbcUrl = "jdbc:splice://localhost:1527/splicedb;user=splice;password=admin;useSpark=true";
        Connection conn = DriverManager.getConnection(jdbcUrl);

        SparkSession sparkSession = SpliceSpark.getSession();

        //Specify the data for predictions
        Map<String, String> options = new HashMap<String, String>();
        options.put("driver", "com.splicemachine.db.jdbc.ClientDriver");
        options.put("url", jdbcUrl);
        options.put("dbtable", sensorTableName);

        //Load Model to use for predictins
        CrossValidatorModel cvModel = CrossValidatorModel.load(savedModelPath);

        //Keep checking for new data and make predictions
        while (loopinterval > 0) {
            //Sensor data requiring predictions
            Dataset<Row> sensords = sparkSession.read().format("jdbc").options(options).load();

            //prepare data
            sensords = sensords.na().fill(0);

            //make predictions
            Dataset<Row> predictions = cvModel.transform(sensords)
                    .select("ENGINE_TYPE", "UNIT", "TIME", "prediction")
                    .withColumnRenamed("prediction", "PREDICTION");

            //Save predictions
            String fileName = "temp_pred_" + RandomStringUtils.randomAlphabetic(6).toLowerCase();

            predictions.write().mode(SaveMode.Append).csv("/tmp/data_pred/predictions");

            //Mark records for which predictions are made
            PreparedStatement pStmtDel = conn.prepareStatement(
                    "delete  from IOT.TO_PROCESS_SENSOR s where exists (select 1 from IOT.PREDICTIONS_EXT p where p.engine_type = s.engine_type and p.unit= s.unit and p.time=s.time )");
            pStmtDel.execute();
            pStmtDel.close();
        }

    } catch (SQLException sqle) {
        System.out.println("Error  :::::" + sqle.toString());
        LOG.error("Exception in getColumnStatistics", sqle);
        sqle.printStackTrace();
    }

}

From source file:com.commander4j.sys.JHost.java

@SuppressWarnings("rawtypes")
public static void deRegisterDrivers() {
    java.util.Enumeration e = java.sql.DriverManager.getDrivers();
    while (e.hasMoreElements()) {
        Object driverAsObject = e.nextElement();
        System.out.println("JDBC Driver=" + driverAsObject);
        try {//from  ww  w.  j  a v a  2s .com
            DriverManager.deregisterDriver((java.sql.Driver) driverAsObject);
        } catch (SQLException e1) {
            e1.printStackTrace();
        }
    }
}

From source file:azkaban.project.JdbcProjectImplTest.java

@AfterClass
public static void destroyDB() {
    try {/*from  ww w  . j  a  v  a 2  s  . com*/
        dbOperator.update("DROP ALL OBJECTS");
        dbOperator.update("SHUTDOWN");
    } catch (final SQLException e) {
        e.printStackTrace();
    }
}

From source file:ext.tmt.utils.LWCUtil.java

/**
 * ?Key,Value?/*from w  w w . j av a 2 s .  c o m*/
 * @param key IBA
 * @param value IBA
 * @param type 
 * @return
 */
public static List<Persistable> getObjectByIBA(Map<String, String> ibaValues, String type) {
    Debug.P("---getObjectByIBA: ibaValues:" + ibaValues);
    List<Persistable> result = null;
    String sql = null;
    if (ibaValues != null && ibaValues.size() > 0) {
        StringBuffer bf = new StringBuffer();
        List<String> paramList = new ArrayList<String>();
        bf.append("and  (");
        //IBA?
        for (Iterator<?> ite = ibaValues.keySet().iterator(); ite.hasNext();) {
            String key = (String) ite.next();
            bf.append("d1.name=?");
            paramList.add(key);
            String value = ibaValues.get(key);
            if (StringUtils.isEmpty(value)) {
                bf.append("and  ").append("v1.value is Null");
            } else {
                bf.append("and  ").append("v1.value=?");
                paramList.add(value);
            }
        }
        bf.append(")");
        //IBA?
        String queryIBACond = bf.toString();
        Debug.P("--->>Query IBA Param:" + queryIBACond);
        if ("wt.part.WTPart".contains(type)) {//
            sql = "select M1.NAME,M1.WTPARTNUMBER as OBJECTNUMBER  FROM  STRINGVALUE v1 ,STRINGDEFINITION d1,WTPART p1,WTPARTMASTER m1 where D1.IDA2A2=v1.ida3a6 and v1.IDA3A4=p1.IDA2A2 and p1.IDA3MASTERREFERENCE=M1.IDA2A2 and d1.name=?  and v1.value=?";
        } else if ("wt.epm.EPMDocument".contains(type)) {
            sql = "select M1.NAME,M1.DOCUMENTNUMBER as OBJECTNUMBER  FROM  STRINGVALUE v1 ,STRINGDEFINITION d1,EPMDOCUMENT e1,EPMDOCUMENTMASTER m1 where D1.IDA2A2=v1.ida3a6 and v1.IDA3A4=e1.IDA2A2 and e1.IDA3MASTERREFERENCE=M1.IDA2A2 and d1.name=?  and v1.value=? ";
        } else if ("wt.doc.WTDocument".contains(type)) {
            sql = "select M1.NAME,M1.WTDOCUMENTNUMBER as OBJECTNUMBER FROM  STRINGVALUE v1 ,STRINGDEFINITION d1,WTDOCUMENT t1,WTDOCUMENTMASTER m1 where D1.IDA2A2=v1.ida3a6 and v1.IDA3A4=t1.IDA2A2 and t1.IDA3MASTERREFERENCE=M1.IDA2A2 and d1.name=?  and v1.value=?";
        }
        String[] params = new String[paramList.size()];
        params = paramList.toArray(params);
        Debug.P("---->>>SQL:" + sql);
        Debug.P("------>>>>SQL param:" + paramList);
        try {
            List<Hashtable<String, String>> datas = UserDefQueryUtil.commonQuery(sql, params);
            if (datas != null && datas.size() > 0) {
                Debug.P("---->>getObjectIBA  Size:" + datas.size());
                result = new ArrayList<Persistable>();
                for (int i = 0; i < datas.size(); i++) {
                    Hashtable<String, String> data_rows = datas.get(i);
                    for (Iterator<?> ite = data_rows.keySet().iterator(); ite.hasNext();) {
                        String keyStr = (String) ite.next();
                        if (keyStr.equalsIgnoreCase("OBJECTNUMBER")) {
                            String valueStr = data_rows.get("OBJECTNUMBER");
                            Persistable object = GenericUtil.getObjectByNumber(valueStr);
                            result.add(object);
                        }
                    }
                }
            }
        } catch (SQLException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    return result;
}