Example usage for java.sql BatchUpdateException printStackTrace

List of usage examples for java.sql BatchUpdateException printStackTrace

Introduction

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

Prototype

public void printStackTrace() 

Source Link

Document

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

Usage

From source file:Main.java

public static void main(String[] args) throws Exception {
    Connection conn = getConnection();
    conn.setAutoCommit(false);/* ww  w.j a  v a 2 s.c  o 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.setString(1, "1");
    pstmt.setString(2, "name1");
    pstmt.addBatch();

    pstmt.setString(1, "2");
    pstmt.setString(2, "name2");
    pstmt.addBatch();

    try {
        // execute the batch
        int[] updateCounts = pstmt.executeBatch();
    } catch (BatchUpdateException e) {
        int[] updateCounts = e.getUpdateCounts();
        checkUpdateCounts(updateCounts);
        try {
            conn.rollback();
        } catch (Exception e2) {
            e.printStackTrace();
            System.exit(1);
        }
    }
    // since there were no errors, commit
    conn.commit();

    ResultSet rs = st.executeQuery("SELECT * FROM survey");
    outputResultSet(rs);

    rs.close();
    st.close();
    conn.close();
}

From source file:module.entities.NameFinder.DB.java

public static void insertJsonResponse(int curConsId, TreeMap<Integer, String> input) throws SQLException {
    try {//ww w .  java  2  s.  c  o  m
        String insertSQL = "INSERT INTO enhancedentities " + "(consultation_id,article_id,json_text) VALUES"
                + "(?,?,?);";
        PreparedStatement prepStatement = connection.prepareStatement(insertSQL);
        //            connection.setAutoCommit(false);
        for (int curArticle : input.keySet()) {
            String json_text = input.get(curArticle);
            prepStatement.setInt(1, curConsId);
            prepStatement.setInt(2, curArticle);
            prepStatement.setString(3, json_text);
            //                prepStatement.executeUpdate();
            prepStatement.addBatch();
        }
        prepStatement.executeBatch();
        //            connection.commit();
        prepStatement.close();

        //            for (int i = 0; i<x.length; i++){
        //                System.out.println(x[i]);
        //            }
    } catch (BatchUpdateException ex) {
        ex.printStackTrace();
        //            System.out.println(ex.getNextException());
    }
}

From source file:com.medlog.webservice.services.tone.ToneProcessorFactory.java

private static ArrayList<Integer> processTone(DbConnection dbc, ToneAnalysis tone, int diaryID) {
    CallableStatement cs = null;/*from w w  w. ja  v a2 s .  co  m*/
    String cat_id = "";
    ArrayList<Integer> results = new ArrayList<Integer>();
    try {
        //category , tone , sentance,score,text
        List<com.ibm.watson.developer_cloud.tone_analyzer.v3.model.ToneCategory> to = tone.getDocumentTone()
                .getTones();
        Connection conn = dbc.getConnnection();

        cs = conn.prepareCall(new StringBuilder().append("{call spDiaryTextScoreInsert(").append(diaryID)
                .append(",?,?,?,?,?)}").toString());
        conn.setAutoCommit(false);
        cs.setInt(3, 0);
        cs.setNull(5, java.sql.Types.NVARCHAR);// cat_id);

        for (com.ibm.watson.developer_cloud.tone_analyzer.v3.model.ToneCategory docTC : to) {
            cat_id = docTC.getId();
            cs.setString(1, cat_id);
            for (ToneScore s : docTC.getTones()) {
                cs.setString(2, s.getId());
                cs.setDouble(4, s.getScore());
                cs.addBatch();
            }

        }
        System.out.println("com.medlog.webservice.util.ToneAnalyzerExample.processTone() Process "
                + tone.getSentencesTone().size() + " sentances.");
        int[] docRes = cs.executeBatch();
        List l = Arrays.asList(docRes);
        results.addAll(l);

        cs.clearBatch();
        System.out.println("com.medlog.webservice.util.ToneAnalyzerExample.processTone() result --- "
                + ArrayUtils.toString(docRes));
        int[] sentRes = null;
        for (SentenceTone sentT : tone.getSentencesTone()) {
            to = sentT.getTones();
            cs.setInt(3, sentT.getId());
            cs.setString(5, toS(sentT.getText()).trim());
            for (com.ibm.watson.developer_cloud.tone_analyzer.v3.model.ToneCategory docTC : to) {
                cat_id = docTC.getId();
                cs.setString(1, cat_id);

                try {
                    for (ToneScore s : docTC.getTones()) {
                        cs.setString(2, s.getId());
                        cs.setDouble(4, s.getScore());
                        cs.addBatch();
                    }
                    if (DEBUG) {
                        DbUtl.getWarningsFromStatement(cs);
                    }
                    //                        sentRes = cs.executeBatch();
                    //                        List l = Arrays.asList(sentRes);
                    //                        results.addAll(l);
                } catch (SQLException s) {
                    System.err.println(
                            "com.medlog.webservice.services.tone.ToneProcessorFactory.processTone(loop)"
                                    + DbUtl.printJDBCExceptionMsg(s));
                    s.printStackTrace();
                } catch (Exception s) {

                }

                System.out.println("com.medlog.webservice.util.ToneAnalyzerExample.processTone() result["
                        + sentT.getId() + "] " + ArrayUtils.toString(sentRes));
            }
        }
        sentRes = cs.executeBatch();
        try {
            l = Arrays.asList(sentRes);
            results.addAll(l);
            conn.setAutoCommit(true);
            cs.clearBatch();
        } catch (Exception e) {
            e.printStackTrace();
            try {
                conn.setAutoCommit(true);
            } catch (Exception eeee) {
                eeee.printStackTrace();
            }
        }
    } catch (BatchUpdateException ex) {
        Logger.getLogger(ToneAnalyzerExample.class.getName()).log(Level.SEVERE, null, ex);
        System.err.println("com.medlog.webservice.services.tone.ToneProcessorFactory.processTone(batch)"
                + DbUtl.printBatchUpdateException(ex));

    } catch (SQLTimeoutException ex) {

        Logger.getLogger(ToneAnalyzerExample.class.getName()).log(Level.SEVERE, null, ex);
        ex.printStackTrace();
    } catch (SQLException ex) {
        Logger.getLogger(ToneAnalyzerExample.class.getName()).log(Level.SEVERE, null, ex);
        System.err.println("com.medlog.webservice.services.tone.ToneProcessorFactory.processTone(meth)"
                + DbUtl.printJDBCExceptionMsg(ex));

    } finally {
        DbUtl.close(cs);
    }
    return results;
}

From source file:org.fao.geonet.MetadataResourceDatabaseMigration.java

@Override
public void update(Connection connection) throws SQLException {
    Log.debug(Geonet.DB, "MetadataResourceDatabaseMigration");

    try (PreparedStatement update = connection.prepareStatement("UPDATE metadata SET data=? WHERE id=?")) {
        try (Statement statement = connection.createStatement();
                ResultSet resultSet = statement
                        .executeQuery("SELECT data,id,uuid FROM metadata WHERE isharvested = 'n'")) {
            int numInBatch = 0;
            final SettingManager settingManager = applicationContext.getBean(SettingManager.class);

            while (resultSet.next()) {
                final Element xml = Xml.loadString(resultSet.getString(1), false);
                final int id = resultSet.getInt(2);
                final String uuid = resultSet.getString(3);
                boolean changed = updateMetadataResourcesLink(xml, uuid, settingManager);
                if (changed) {
                    String updatedData = Xml.getString(xml);
                    update.setString(1, updatedData);
                    update.setInt(2, id);
                    update.addBatch();//w w  w.jav  a 2 s  . c om
                    numInBatch++;
                    if (numInBatch > 200) {
                        update.executeBatch();
                        numInBatch = 0;
                    }
                }
            }
            update.executeBatch();
        } catch (java.sql.BatchUpdateException e) {
            System.out.println("Error occurred while updating resource links:");
            e.printStackTrace();
            SQLException next = e.getNextException();
            while (next != null) {
                System.err.println("Next error: ");
                next.printStackTrace();
                next = e.getNextException();
            }

            throw new RuntimeException(e);
        } catch (Exception e) {
            throw new Error(e);
        }
    }
}

From source file:org.apache.marmotta.kiwi.reasoner.test.persistence.JustificationPersistenceTest.java

/**
 * Test 1: create some triples through a repository connection (some inferred, some base), load a program, and
 * store justifications for the inferred triples based on rules and base triples. Test the different listing
 * functions.//from   w  ww  .  j a  va  2  s .c om
 *
 */
@Test
public void testStoreJustifications() throws Exception {
    KiWiValueFactory v = (KiWiValueFactory) repository.getValueFactory();

    URI ctxb = v.createURI("http://localhost/context/default");
    URI ctxi = v.createURI("http://localhost/context/inferred");

    URI s1 = v.createURI("http://localhost/resource/" + RandomStringUtils.randomAlphanumeric(8));
    URI s2 = v.createURI("http://localhost/resource/" + RandomStringUtils.randomAlphanumeric(8));
    URI s3 = v.createURI("http://localhost/resource/" + RandomStringUtils.randomAlphanumeric(8));
    URI p1 = v.createURI("http://localhost/resource/" + RandomStringUtils.randomAlphanumeric(8));
    URI p2 = v.createURI("http://localhost/resource/" + RandomStringUtils.randomAlphanumeric(8));
    URI o1 = v.createURI("http://localhost/resource/" + RandomStringUtils.randomAlphanumeric(8));
    URI o2 = v.createURI("http://localhost/resource/" + RandomStringUtils.randomAlphanumeric(8));
    URI o3 = v.createURI("http://localhost/resource/" + RandomStringUtils.randomAlphanumeric(8));

    // first, load a sample program (it does not really matter what it actually contains, since we are not really
    // running the reasoner)
    KWRLProgramParserBase parser = new KWRLProgramParser(v,
            this.getClass().getResourceAsStream("test-001.kwrl"));
    Program p = parser.parseProgram();
    p.setName("test-001");

    KiWiReasoningConnection connection = rpersistence.getConnection();
    try {
        // should not throw an exception and the program should have a database ID afterwards
        connection.storeProgram(p);
        connection.commit();
    } finally {
        connection.close();
    }

    // then get a connection to the repository and create a number of triples, some inferred and some base
    RepositoryConnection con = repository.getConnection();
    try {
        con.add(s1, p1, o1);
        con.add(s2, p1, o2);
        con.add(s3, p1, o3);

        con.add(s1, p2, o1, ctxi);
        con.add(s2, p2, o2, ctxi);
        con.add(s3, p2, o3, ctxi);

        con.commit();
    } finally {
        con.close();
    }

    connection = rpersistence.getConnection();
    try {
        // retrieve the persisted triples and put them into two sets to build justifications
        List<Statement> baseTriples = asList(
                connection.listTriples(null, null, null, v.convert(ctxb), false, true));
        List<Statement> infTriples = asList(
                connection.listTriples(null, null, null, v.convert(ctxi), true, true));

        Assert.assertEquals("number of base triples was not 3", 3, baseTriples.size());
        Assert.assertEquals("number of inferred triples was not 3", 3, infTriples.size());

        // we manually update the "inferred" flag for all inferred triples, since this is not possible through the
        // repository API
        PreparedStatement updateInferred = connection.getJDBCConnection()
                .prepareStatement("UPDATE triples SET inferred = true WHERE id = ?");
        for (Statement stmt : infTriples) {
            KiWiTriple triple = (KiWiTriple) stmt;
            updateInferred.setLong(1, triple.getId());
            updateInferred.addBatch();
        }
        updateInferred.executeBatch();
        updateInferred.close();

        // now we create some justifications for the inferred triples and store them
        Set<Justification> justifications = new HashSet<Justification>();
        Justification j1 = new Justification();
        j1.getSupportingRules().add(p.getRules().get(0));
        j1.getSupportingRules().add(p.getRules().get(1));
        j1.getSupportingTriples().add((KiWiTriple) baseTriples.get(0));
        j1.getSupportingTriples().add((KiWiTriple) baseTriples.get(1));
        j1.setTriple((KiWiTriple) infTriples.get(0));
        justifications.add(j1);

        Justification j2 = new Justification();
        j2.getSupportingRules().add(p.getRules().get(1));
        j2.getSupportingTriples().add((KiWiTriple) baseTriples.get(1));
        j2.getSupportingTriples().add((KiWiTriple) baseTriples.get(2));
        j2.setTriple((KiWiTriple) infTriples.get(1));
        justifications.add(j2);

        connection.storeJustifications(justifications);
        connection.commit();

        // we should now have two justifications in the database
        PreparedStatement listJustifications = connection.getJDBCConnection()
                .prepareStatement("SELECT count(*) AS count FROM reasoner_justifications");
        ResultSet resultListJustifications = listJustifications.executeQuery();

        Assert.assertTrue(resultListJustifications.next());
        Assert.assertEquals(2, resultListJustifications.getInt("count"));
        resultListJustifications.close();
        connection.commit();

        PreparedStatement listSupportingTriples = connection.getJDBCConnection()
                .prepareStatement("SELECT count(*) AS count FROM reasoner_just_supp_triples");
        ResultSet resultListSupportingTriples = listSupportingTriples.executeQuery();

        Assert.assertTrue(resultListSupportingTriples.next());
        Assert.assertEquals(4, resultListSupportingTriples.getInt("count"));
        resultListSupportingTriples.close();
        connection.commit();

        PreparedStatement listSupportingRules = connection.getJDBCConnection()
                .prepareStatement("SELECT count(*) AS count FROM reasoner_just_supp_rules");
        ResultSet resultListSupportingRules = listSupportingRules.executeQuery();

        Assert.assertTrue(resultListSupportingRules.next());
        Assert.assertEquals(3, resultListSupportingRules.getInt("count"));
        resultListSupportingRules.close();
        connection.commit();

        // *** check listing justifications by base triple (supporting triple)

        // there should now be two justifications based on triple baseTriples.get(1))
        List<Justification> supported1 = asList(
                connection.listJustificationsBySupporting((KiWiTriple) baseTriples.get(1)));
        Assert.assertEquals("number of justifications is wrong", 2, supported1.size());
        Assert.assertThat("justifications differ", supported1, hasItems(j1, j2));

        // only j1 should be supported by triple baseTriples.get(0))
        List<Justification> supported2 = asList(
                connection.listJustificationsBySupporting((KiWiTriple) baseTriples.get(0)));
        Assert.assertEquals("number of justifications is wrong", 1, supported2.size());
        Assert.assertThat("justifications differ", supported2, allOf(hasItem(j1), not(hasItem(j2))));

        // only j2 should be supported by triple baseTriples.get(2))
        List<Justification> supported3 = asList(
                connection.listJustificationsBySupporting((KiWiTriple) baseTriples.get(2)));
        Assert.assertEquals("number of justifications is wrong", 1, supported3.size());
        Assert.assertThat("justifications differ", supported3, allOf(hasItem(j2), not(hasItem(j1))));

        // *** check listing justificatoins by supporting rule

        // there should now be two justifications based on triple p.getRules().get(1)
        List<Justification> supported4 = asList(connection.listJustificationsBySupporting(p.getRules().get(1)));
        Assert.assertEquals("number of justifications is wrong", 2, supported4.size());
        Assert.assertThat("justifications differ", supported4, hasItems(j1, j2));

        // only j1 should be supported by triple p.getRules().get(0)
        List<Justification> supported5 = asList(connection.listJustificationsBySupporting(p.getRules().get(0)));
        Assert.assertEquals("number of justifications is wrong", 1, supported5.size());
        Assert.assertThat("justifications differ", supported5, allOf(hasItem(j1), not(hasItem(j2))));

        // *** check listing justifications by supported (inferred) triple

        // there should now be one justification supporting infTriples.get(0)
        List<Justification> supported6 = asList(
                connection.listJustificationsForTriple((KiWiTriple) infTriples.get(0)));
        Assert.assertEquals("number of justifications is wrong", 1, supported6.size());
        Assert.assertThat("justifications differ", supported6, allOf(hasItem(j1), not(hasItem(j2))));

        // there should now be one justification supporting infTriples.get(1)
        List<Justification> supported7 = asList(
                connection.listJustificationsForTriple((KiWiTriple) infTriples.get(1)));
        Assert.assertEquals("number of justifications is wrong", 1, supported7.size());
        Assert.assertThat("justifications differ", supported7, allOf(hasItem(j2), not(hasItem(j1))));

        // there should now be no justification supporting infTriples.get(2)
        List<Justification> supported8 = asList(
                connection.listJustificationsForTriple((KiWiTriple) infTriples.get(2)));
        Assert.assertEquals("number of justifications is wrong", 0, supported8.size());

        // *** check listing unsupported triples
        List<KiWiTriple> unsupported = asList(connection.listUnsupportedTriples());
        Assert.assertEquals("number of unsupported triples is wrong", 1, unsupported.size());
        Assert.assertThat("unsupported triples differ", unsupported, hasItem((KiWiTriple) infTriples.get(2)));

        // now we delete justification 2; as a consequence,
        // - there should be only once justification left
        // - there should be two unsupported triples
        connection.deleteJustifications(Collections.singleton(j2));

        // we should now have one justifications in the database
        resultListJustifications = listJustifications.executeQuery();

        Assert.assertTrue(resultListJustifications.next());
        Assert.assertEquals(1, resultListJustifications.getInt("count"));
        resultListJustifications.close();
        connection.commit();

        resultListSupportingTriples = listSupportingTriples.executeQuery();

        Assert.assertTrue(resultListSupportingTriples.next());
        Assert.assertEquals(2, resultListSupportingTriples.getInt("count"));
        resultListSupportingTriples.close();
        connection.commit();

        resultListSupportingRules = listSupportingRules.executeQuery();

        Assert.assertTrue(resultListSupportingRules.next());
        Assert.assertEquals(2, resultListSupportingRules.getInt("count"));
        resultListSupportingRules.close();
        connection.commit();

        List<KiWiTriple> unsupported2 = asList(connection.listUnsupportedTriples());
        Assert.assertEquals("number of unsupported triples is wrong", 2, unsupported2.size());
        Assert.assertThat("unsupported triples differ", unsupported2, hasItem((KiWiTriple) infTriples.get(1)));

    } catch (BatchUpdateException ex) {
        if (ex.getNextException() != null) {
            ex.printStackTrace();
            throw ex.getNextException();
        } else {
            throw ex;
        }
    } finally {
        connection.close();
    }

}