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:de.lsvn.dao.UserDao.java

public void purgeSchedulerEvent(String start, String end, String resource, String eventId,
        Integer sessionOwnerId) {
    connection = DbUtil.getConnection();
    try {// w w  w  . j  a v a 2s.co  m
        PreparedStatement preparedStatement = connection
                .prepareStatement("DELETE FROM events WHERE id=? AND mitgliederId=?");
        preparedStatement.setInt(1, Integer.parseInt(eventId));
        preparedStatement.setInt(2, sessionOwnerId);
        preparedStatement.executeUpdate();
        DbUtil.closePreparedStatement(preparedStatement);
    } catch (SQLException e) {
        e.printStackTrace();
    } finally {
        DbUtil.closeConnection(connection);
    }
}

From source file:gr.osmosis.rcpsamples.contact.db.derby.DerbyContactsDAO.java

public boolean deleteContact(int id) {

    int rows = 0;

    try {//www . j  a  va 2s  .  c om
        StringBuffer sbDelete = new StringBuffer();

        sbDelete.append("DELETE FROM ");
        sbDelete.append(ContactsConstants.CONTACTS_TABLE_NAME);
        sbDelete.append(" WHERE ");
        sbDelete.append(ContactsConstants.CONTACTS_COL_ID + " = " + id);

        DataSource d = DerbyDAOFactory.getDataSource();
        QueryRunner run = new QueryRunner(d);

        rows = run.update(sbDelete.toString());

        if (rows != 1) {
            throw new SQLException("executeUpdate return value: " + rows);
        }

    } catch (SQLException ex) {
        ex.printStackTrace();
        return false;
    }

    return true;

}

From source file:hspc.submissionsprogram.AppDisplay.java

private void displayClarification(ResultSet row) {
    try {/*from  ww  w  .  j a v  a2s .  c  om*/
        String problem = row.getString("problem");
        String text = row.getString("text");
        String response = row.getString("response");
        new ClarificationDisplay(problem, text, response);
    } catch (SQLException ex) {
        ex.printStackTrace();
    }
}

From source file:de.lsvn.dao.UserDao.java

public boolean resetUserPwd(int userId, String newPwd) {
    connection = DbUtil.getConnection();
    try {/*from  w w w  .j  av a2 s.  c o  m*/
        PreparedStatement preparedStatement = connection.prepareStatement(
                "UPDATE authentifizierung JOIN mitglieder ON mitglieder.Id = authentifizierung.AuthentId SET pwd=? WHERE Id=?");
        preparedStatement.setInt(2, userId);
        preparedStatement.setString(1, newPwd);
        preparedStatement.executeUpdate();
        DbUtil.closePreparedStatement(preparedStatement);
        return true;
    } catch (SQLException e) {
        e.printStackTrace();
        return false;
    } finally {
        DbUtil.closeConnection(connection);
    }
}

From source file:gr.seab.r2rml.test.ComplianceTests.java

private void openConnection() {
    connection = null;// w w  w . j a  v a 2  s  .  c  o m

    try {
        Class.forName("org.postgresql.Driver");
        connection = DriverManager.getConnection("jdbc:postgresql://localhost:5432/test", "postgres",
                "postgres");
        //connection = DriverManager.getConnection("jdbc:oracle:thin:@127.0.0.1:1521", "system", "dba");
        //connection = DriverManager.getConnection("jdbc:postgresql://83.212.115.187:5432/ebooks-dspace6", "postgres", "postgres");
    } catch (SQLException e) {
        e.printStackTrace();
    } catch (ClassNotFoundException e) {
        e.printStackTrace();
    }
}

From source file:com.base2.kagura.core.report.connectors.FreemarkerSQLDataReportConnector.java

/**
 * Runs freemarker against the 3 sql queries, then executes them in order.
 * {@inheritDoc}//from w  w  w .j  a v  a 2 s. com
 */
@Override
public void runReport(Map<String, Object> extra) {
    PreparedStatement prestatement = null;
    PreparedStatement poststatement = null;
    PreparedStatement statement = null;
    try {
        getStartConnection();
        if (StringUtils.isNotBlank(presql)) {
            FreemarkerSQLResult prefreemarkerSQLResult = freemakerParams(extra, false, presql);
            prestatement = connection.prepareStatement(prefreemarkerSQLResult.getSql());
            for (int i = 0; i < prefreemarkerSQLResult.getParams().size(); i++) {
                prestatement.setObject(i + 1, prefreemarkerSQLResult.getParams().get(i));
            }
            prestatement.setQueryTimeout(queryTimeout);
            prestatement.execute();
        }
        FreemarkerSQLResult freemarkerSQLResult = freemakerParams(extra, true, freemarkerSql);
        statement = connection.prepareStatement(freemarkerSQLResult.getSql());
        for (int i = 0; i < freemarkerSQLResult.getParams().size(); i++) {
            statement.setObject(i + 1, freemarkerSQLResult.getParams().get(i));
        }
        statement.setQueryTimeout(queryTimeout);
        rows = resultSetToMap(statement.executeQuery());
        if (StringUtils.isNotBlank(postsql)) {
            FreemarkerSQLResult postfreemarkerSQLResult = freemakerParams(extra, false, postsql);
            poststatement = connection.prepareStatement(postfreemarkerSQLResult.getSql());
            for (int i = 0; i < postfreemarkerSQLResult.getParams().size(); i++) {
                poststatement.setObject(i + 1, postfreemarkerSQLResult.getParams().get(i));
            }
            poststatement.setQueryTimeout(queryTimeout);
            poststatement.execute();
        }
    } catch (Exception ex) {
        errors.add(ex.getMessage());
    } finally {
        try {
            if (statement != null && !statement.isClosed()) {
                statement.close();
                statement = null;
            }
            if (prestatement != null && !prestatement.isClosed()) {
                prestatement.close();
                prestatement = null;
            }
            if (poststatement != null && !poststatement.isClosed()) {
                poststatement.close();
                poststatement = null;
            }
            if (connection != null && !connection.isClosed()) {
                connection.close();
                connection = null;
            }
        } catch (SQLException e) {
            errors.add(e.getMessage());
            e.printStackTrace();
        }
    }
}

From source file:desktopsearch.ExploreFiles.java

private void WriteToDB(Integer LinesFinished) {
    try {//ww w  . j  a v  a2s.  c  o m
        BufferedReader buffer = new BufferedReader(new FileReader(Location + "/.DSearch/FilesList.sql"));
        int count = 0;
        String SQL = null;

        while ((SQL = buffer.readLine()) != null) {

            if (count < LinesFinished) {
                count++;
                continue;
            }
            statement.addBatch(SQL);
            count++;
            if (count % 1000 == 0) {
                try {

                    statement.executeBatch();
                    SQL = "UPDATE IndexingInfo SET NoOfEntriesFinished=" + count
                            + " WHERE IndexID IN (SELECT max(IndexID) AS MaxID FROM IndexingInfo)";
                    statement.executeUpdate(SQL);
                    connection.commit();

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

        SQL = "UPDATE IndexingInfo SET NoOfEntriesFinished=" + count
                + ",EndTime=CURRENT_TIMESTAMP WHERE IndexID IN (SELECT max(IndexID) AS MaxID FROM IndexingInfo)";
        statement.addBatch(SQL);
        statement.executeBatch();
        connection.commit();
        UpdateIndexingProgress(IndexingFinishedIndicator);

    } catch (Exception ex) {
        ex.printStackTrace();
    }

}

From source file:jmdbtools.JMdbTools.java

private int[] insertData(Table dataTable, DbTable dbTable, Connection conn) {
    Statement stmt = null;/*ww  w .j a  va 2  s  .c  o m*/
    int[] execStatus = new int[0];
    try {
        stmt = conn.createStatement();
        log("Creating Insert Statements:" + dbTable.getName(), "info");

        for (Row row : dataTable) {
            InsertQuery insertQuery = new InsertQuery(dbTable);
            for (Map.Entry<String, Object> col : row.entrySet()) {
                //We had to add crap to the column name, so have to muck about to get match

                DbColumn column = dbTable.findColumn(fixColumnName(col.getKey()));

                if (col.getValue() != null) {
                    if (column.getTypeNameSQL().equalsIgnoreCase("DATE")
                            || column.getTypeNameSQL().equalsIgnoreCase("DATETIME")) {
                        java.sql.Timestamp sqlDate = new java.sql.Timestamp(((Date) col.getValue()).getTime());
                        //log(sqlDate.toString(), "debug");
                        insertQuery.addColumn(column, sqlDate);
                    } else {
                        insertQuery.addColumn(column, col.getValue());
                    }
                }
            }
            stmt.addBatch(insertQuery.validate().toString());
        }
        log("Executing Insert", "info");

        execStatus = stmt.executeBatch();
    } catch (SQLException e) {
        e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates.
    }

    return execStatus;

}

From source file:com.zimbra.cs.db.JdbcClient.java

private void runSql(Connection conn, String sql) {
    Matcher m = PAT_SELECT.matcher(sql);

    if (m.find()) {
        // Run query and display results 
        try {//w  w  w  . j a  v  a 2 s  .  c o  m
            Statement stmt = conn.createStatement();
            ResultSet rs = stmt.executeQuery(sql);
            ResultSetMetaData md = rs.getMetaData();
            int colCount = md.getColumnCount();
            List<Object[]> firstRows = new ArrayList<Object[]>();
            int rowCount = 0;

            // Set initial column widths based on column labels
            int[] colWidths = new int[colCount];
            if (mShowColumnNames) {
                for (int i = 0; i < colCount; i++) {
                    String name = md.getColumnLabel(i + 1);
                    if (name.length() > colWidths[i]) {
                        colWidths[i] = name.length();
                    }
                }
            }

            // Read first 1000 rows first to calculate column widths for printing
            while (rowCount < 1000 && rs.next()) {
                Object[] row = getCurrentRow(rs);
                for (int i = 0; i < colCount; i++) {
                    Object o = row[i];
                    int width = (o == null) ? NULL.length() : (o.toString()).length();
                    if (width > colWidths[i]) {
                        colWidths[i] = width;
                    }
                }
                firstRows.add(row);
                rowCount++;
            }

            // Print first rows
            if (!mBatch && mShowColumnNames) {
                // Skip if we're in batch mode.  If not displaying column names, don't
                // print the first divider.
                printDivider(colWidths);
            }
            if (mShowColumnNames) {
                String[] colNames = new String[colCount];
                for (int i = 0; i < colCount; i++) {
                    colNames[i] = md.getColumnLabel(i + 1);
                }
                printRow(colNames, colWidths);
            }
            if (!mBatch) {
                printDivider(colWidths);
            }
            for (Object[] row : firstRows) {
                printRow(row, colWidths);
            }

            // Print any remaining rows
            while (rs.next()) {
                Object[] row = getCurrentRow(rs);
                printRow(row, colWidths);
            }
            if (!mBatch) {
                printDivider(colWidths);
            }
            rs.close();
            stmt.close();
        } catch (SQLException e) {
            e.printStackTrace();
            System.err.println(e.getMessage());
        }
    } else {
        // Run statement
        try {
            Statement stmt = conn.createStatement();
            int numRows = stmt.executeUpdate(sql);
            stmt.close();
            System.out.println("Updated " + numRows + " rows");
        } catch (SQLException e) {
            System.err.println(e.getMessage());
        }
    }
}

From source file:edu.purdue.pivot.skwiki.server.ImageUploaderServlet.java

@Override
public String executeAction(HttpServletRequest request, List<FileItem> sessionFiles)
        throws UploadActionException {

    connection = null;// www .j a  v  a  2s.c o  m
    Statement st = null;

    /* read database details from file */
    BufferedReader br;
    current_project_name = "";
    main_database_name = "";

    try {
        br = new BufferedReader(new FileReader(this.getServletContext().getRealPath("/serverConfig.txt")));
        StringBuilder sb = new StringBuilder();
        String line = br.readLine();

        while (line != null) {
            String first = line.substring(0, line.lastIndexOf(':'));
            String last = line.substring(line.lastIndexOf(':') + 1);

            if (first.contains("content_database")) {
                current_project_name = last;
            }

            if (first.contains("owner_database")) {
                main_database_name = last;
            }

            if (first.contains("username")) {
                postgres_name = last;
            }

            if (first.contains("password")) {
                postgres_password = last;
            }

            sb.append(line);
            sb.append(System.lineSeparator());
            line = br.readLine();
        }

        //String everything = sb.toString();
        //System.out.println("file: "+everything);
        br.close();

    } catch (Exception e1) {
        // TODO Auto-generated catch block
        e1.printStackTrace();
    } finally {

    }

    try {
        connection = DriverManager.getConnection("jdbc:postgresql://127.0.0.1:5432/" + current_project_name,
                "postgres", "fujiko");
    } catch (SQLException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

    String response = "";
    int cont = 0;
    for (FileItem item : sessionFiles) {
        if (false == item.isFormField()) {
            cont++;
            try {
                String uuid = UUID.randomUUID().toString();
                String saveName = uuid + '.' + FilenameUtils.getExtension(item.getName());

                //               String saveName = item.getName();

                //write to database
                File file = new File(saveName);
                item.write(file);

                // / Save a list with the received files
                receivedFiles.put(item.getFieldName(), file);
                receivedContentTypes.put(item.getFieldName(), item.getContentType());
                receivedFilePaths.put(item.getFieldName(), file.getAbsolutePath());

                // / Send a customized message to the client.
                response += "File saved as " + file.getAbsolutePath();

                //write filename to database

                String selectStr = "insert into images values (" + "\'" + item.getFieldName() + "\'," + "\'"
                        + file.getAbsolutePath() + "\'" + ")";
                st = connection.createStatement();
                int textReturnCode = st.executeUpdate(selectStr);

            } catch (Exception e) {
                throw new UploadActionException(e.getMessage());
            }
        }
    }

    // / Remove files from session because we have a copy of them
    removeSessionFileItems(request);

    // / Send your customized message to the client.
    return response;
}