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:bq.jpa.demo.query.nativequery.service.NativeQueryService.java

/**
 * use jdbc directly/*from   w  ww .j a v  a2 s  .  c  o  m*/
 */
public void doJDBCQuery() {
    Connection conn = null;
    PreparedStatement ps = null;

    try {
        conn = ds.getConnection();
        ps = conn.prepareStatement(EMPLOYEE_QUERY);
        ps.setLong(1, 1500);
        ResultSet rs = ps.executeQuery();

        List<Employee> employees = new ArrayList<>();
        while (rs.next()) {
            Employee employee = new Employee();
            employee.setId(rs.getInt("pk_employee"));
            employee.setName(rs.getString("name"));
            employee.setSalary(rs.getInt("salary"));
            employees.add(employee);
        }

        ResultViewer.showResult(employees, EMPLOYEE_QUERY);
    } catch (SQLException e) {
        e.printStackTrace();
    } finally {
        try {
            ps.close();
            conn.close();
        } catch (SQLException e) {
            e.printStackTrace();
        }

    }

}

From source file:com.orientechnologies.orient.jdbc.spring.CorenetThread.java

public void run() {
    try {//from   w  w  w .  j a va2  s  . c om
        PreparedStatement queryPrepStatement = connection
                .prepareStatement("SELECT FROM OGraphVertex WHERE name = ?");
        queryPrepStatement.setString(1, ROOT_VERTEX_NAME);
        ResultSet rs = queryPrepStatement.executeQuery();

        Assert.assertTrue(NAME + "There is no vertex with name " + ROOT_VERTEX_NAME, rs.first());
        //the RID is always the first element in the RS
        Object vertexId = rs.getObject(1);
        OrientGraph g = connection.unwrap(OrientGraph.class);
        Vertex v = g.getVertex(vertexId);
        Assert.assertNotNull(NAME + "There is no vertex for rid ", v);

        Iterator<Edge> containmentRels = v.getEdges(Direction.OUT, SUPPLY_RELATION_EDGE).iterator();
        Assert.assertTrue(
                NAME + "There is no edge with label '" + SUPPLY_RELATION_EDGE + "' coming from " + v.toString(),
                containmentRels.hasNext());

        String prefix = NAME + "Values:: ";
        StringBuilder textToBePrinted = new StringBuilder(prefix);
        Edge currentRel;
        while (containmentRels.hasNext()) {
            currentRel = containmentRels.next();
            if (textToBePrinted.length() == prefix.length())
                textToBePrinted.append(currentRel.getVertex(Direction.IN).getProperty("name").toString());
            else
                textToBePrinted
                        .append(", " + currentRel.getVertex(Direction.IN).getProperty("name").toString());
        }
        System.out.println(textToBePrinted);
    } catch (SQLException e) {
        e.printStackTrace();
        Assert.fail();
    }

}

From source file:it.itis.pertini.falessi.tunes.services.AbstractService.java

protected final Collection<E> getAll(String queryId) {
    try {/*from   ww w .  j ava  2s.com*/
        return queryRunner.query(getQuery(queryId), entityListHandler);
    } catch (SQLException e) {
        e.printStackTrace();
        throw new WebApplicationException(new ResponseBuilderImpl().entity(toErrorMessage(e))
                .status(Response.Status.INTERNAL_SERVER_ERROR).build());
    }
}

From source file:idp.mysql_con.java

public void export_csv() {
    mysql_conn();/*www.j  av a2 s  . c om*/
    for (int i = 0; i < gui.jTabbedPane1.getTabCount(); i++) {
        String file_path = System.getProperty("user.dir") + "\\src\\main\\temp\\csv\\"
                + gui.jTabbedPane1.getTitleAt(i);
        String table = removeExtension(gui.jTabbedPane1.getTitleAt(i)).toLowerCase();
        file_path = file_path.replace("\\", "/");
        try {
            String sql = "LOAD DATA LOCAL INFILE '" + file_path + "' INTO TABLE " + table
                    + " CHARACTER SET 'utf8' FIELDS TERMINATED BY ',' LINES TERMINATED BY '\\n'";
            System.out.println(sql);
            Statement st = con.createStatement();
            st.execute(sql);

        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
}

From source file:com.persistent.cloudninja.dao.impl.PartitionStatsAndBWUsageDaoImpl.java

/**
 * Get the DB size for a tenant./*  www  .ja v a2 s.co  m*/
 * 
 * @param tenantId.
 * @return the DB size.
 */
@Override
public long getDBSize(String tenantId) {
    long dbSize = 0;
    Connection connection = null;
    PreparedStatement preparedStatement = null;
    try {
        connection = provisionConnectionUtility.getConnection(url, "tnt_" + tenantId, MASTER_DB_USER,
                MASTER_DB_PSWD);
        preparedStatement = connection
                .prepareStatement("SELECT SUM(reserved_page_count)* 8 FROM sys.dm_db_partition_stats");
        ResultSet resultSet = preparedStatement.executeQuery();
        if (resultSet.next()) {
            dbSize = resultSet.getLong(1);
        }
    } catch (SQLException e) {
        e.printStackTrace();
    } finally {
        provisionConnectionUtility.closeStatement(preparedStatement);
        provisionConnectionUtility.closeConnection(connection);
    }
    return dbSize;
}

From source file:ClassUsingMySQL.java

public ClassUsingMySQL() {
    ApplicationContext context = new ClassPathXmlApplicationContext(new String[] { "spring.xml" });

    Connection connection = null;
    try {//from   w ww .  j a v  a 2  s.  c o  m
        // Load the JDBC driver
        String driverName = "com.mysql.jdbc.Driver";
        // Class.forName(driverName);

        // Create a connection to the database
        String serverName = "localhost";
        String mydatabase = "operative";
        String url = "jdbc:mysql://" + serverName + "/" + mydatabase;
        String username = "root";
        String password = "";

        BoneCPDataSource ds = new BoneCPDataSource();
        ds.setDriverClass(driverName);
        ds.setJdbcUrl(url);
        ds.setUsername(username);
        ds.setPassword(password);

        connection = ds.getConnection();

        Statement stmt = connection.createStatement();
        @SuppressWarnings("unused")
        ResultSet rs = stmt.executeQuery("SELECT 1");
        System.out.println("Connection established to mysql: " + connection);
        // } catch (ClassNotFoundException e) {
        // System.err.println(e);
        // e.printStackTrace();
    } catch (SQLException e) {
        System.err.println(e);
        e.printStackTrace();
    } finally {
        try {
            if (connection != null)
                connection.close();
        } catch (SQLException e) {
            System.err.println("Couldn't close connection. This might result in a connection leak.");
            e.printStackTrace();
        }
    }
}

From source file:net.firejack.platform.model.config.listener.ConfigContextLoaderListener.java

@Override
public void contextDestroyed(ServletContextEvent event) {
    try {/*from   w  w w.ja v a  2 s . c om*/
        Map<String, BasicDataSource> dataSources = getCurrentWebApplicationContext()
                .getBeansOfType(BasicDataSource.class);
        for (BasicDataSource dataSource : dataSources.values()) {
            try {
                dataSource.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }

        Enumeration<Driver> drivers = DriverManager.getDrivers();
        while (drivers.hasMoreElements()) {
            try {
                DriverManager.deregisterDriver(drivers.nextElement());
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }

        JAXBContextCache.clearCaches();
        ClassFactory.cleanCache();
        CachedIntrospectionResults.clearClassLoader(getClass().getClassLoader());
    } finally {
        super.contextDestroyed(event);
    }
}

From source file:org.projecthdata.ehr.viewer.service.HDataSyncService.java

/**
 * Clears out all root and section data, retrieves the current root document
 * and atom feeds] , and adds their information to the database.
 *//* w w  w .j av a 2 s  . c  om*/
private void onSyncRoot() {
    prefs.edit().putString(Constants.PREF_ROOT_SYNC_STATE, SyncState.WORKING.toString()).commit();
    // TODO: check for connection, launch OAuth activity, resume sync
    try {
        Dao<RootEntry, Integer> rootDao = hDataOrmManager.getDatabaseHelper().getRootEntryDao();
        // clear out existing data
        for (RootEntry entry : rootDao.queryForAll()) {
            entry.getSectionMetadata().clear();
            rootDao.delete(entry);
        }
        // fetch new data and add it to the database
        // use the connection to get the root document
        Connection<HData> connection = connectionRepository.getPrimaryConnection(HData.class);

        RootOperations rootOperations = connection.getApi().getRootOperations();
        Root root = rootOperations.getRoot();
        for (Section section : root.getSections()) {
            processSection(rootOperations, section);
        }
    } catch (SQLException e) {
        e.printStackTrace();
        Log.e(TAG, Log.getStackTraceString(e));
    }
    prefs.edit().putString(Constants.PREF_ROOT_SYNC_STATE, SyncState.READY.toString()).commit();
}

From source file:image.JdbcInsertFileOne.java

public void enregistrer(String path, String type, Voiture voiture, String numPac) {

    String url = "jdbc:mysql://localhost:3306/loc_voiture_db";
    String user = "root";
    String password = "";

    String filePath = path;//from   ww w.  jav  a  2 s . co m
    List<Parc> parcs = metier.listerParc();

    for (Iterator<Parc> iterator = parcs.iterator(); iterator.hasNext();) {
        Parc next = iterator.next();
        if (next.getNumParc().equals(numPac)) {
            idParc = next.getIdPac();
            break;
        }
    }

    try {
        Connection conn = DriverManager.getConnection(url, user, password);

        String sql = "INSERT INTO `voiture` (`immatriculation_voiture`,"
                + " `marque_voiture`, `modele_voiture`, `categorie_voiture`, `couleur_voiture`, "
                + "`carburant_voiture`, `boite_vitesse_voiture`, `climatisation_voiture`, "
                + "`nbr_portes_voiture`, `nbr_places_voiture`, `type_voiture`, `etat_voiture`, "
                + "`id_pac_voiture`, `annee_mise_service`, `type`,`image`, `prix_par_jour_3jour`,"
                + " `prix_par_jour_1semaine`)" + " values (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)";
        PreparedStatement statement = conn.prepareStatement(sql);
        statement.setString(1, voiture.getImmatriculationVoiture());
        statement.setString(2, voiture.getMarqueVoiture());
        statement.setString(3, voiture.getModeleVoiture());
        statement.setString(4, voiture.getCategorieVoiture());
        statement.setString(5, voiture.getCouleurVoiture());
        statement.setString(6, voiture.getCarburantVoiture());
        statement.setString(7, voiture.getBoiteVitesseVoiture());

        statement.setString(8, voiture.getClimatisationVoiture());
        statement.setInt(9, voiture.getNbrPortesVoiture());
        statement.setInt(10, voiture.getNbrPortesVoiture());
        statement.setString(11, voiture.getTypeVoiture());
        statement.setString(12, voiture.getEtatVoiture());
        statement.setInt(13, idParc);
        statement.setString(14, voiture.getAnneeMiseService());
        statement.setString(15, type);

        InputStream inputStream = new FileInputStream(new File(filePath));

        statement.setBlob(16, inputStream);
        statement.setString(17, voiture.getPrixParJour3jour());
        statement.setString(18, voiture.getPrixParJour1semaine());

        int row = statement.executeUpdate();
        if (row > 0) {
            System.out.println("A contact was inserted with photo image.");
        }
        conn.close();
    } catch (SQLException ex) {
        ex.printStackTrace();
    } catch (IOException ex) {
        ex.printStackTrace();
    }
}

From source file:jlp.aspectj.test.MainDBCPtest.java

public void run() {
    while (running) {
        Connection con = null;/*w  w w  . j  av a 2s .c om*/
        Statement stmt = null;
        ResultSet rs = null;
        try {

            con = bds.getConnection();

            stmt = con.createStatement();
            rs = stmt.executeQuery("SELECT * FROM javatest.testdata");
            Thread.sleep(100);
            // while (rs.next())
            // System.out.println(rs.getString(1));
        } catch (SQLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

        catch (InterruptedException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } finally {
            // i try to be neurotic about ResourceManagement,
            // explicitly closing each resource
            // but if you are in the habit of only closing
            // parent resources (e.g. the Connection) and
            // letting them close their children, all
            // c3p0 DataSources will properly deal.
            attemptClose(rs);
            attemptClose(stmt);
            attemptClose(con);
        }
    }
}