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:com.cloudera.sqoop.manager.CubridManagerImportTest.java

public void setUpData(String tableName, boolean nullEntry) {
    SqoopOptions options = new SqoopOptions(CubridTestUtils.getConnectString(), tableName);
    options.setUsername(CubridTestUtils.getCurrentUser());
    options.setPassword(CubridTestUtils.getPassword());

    LOG.debug("Setting up another CubridImport test: " + CubridTestUtils.getConnectString());

    manager = new CubridManager(options);

    Connection connection = null;
    Statement st = null;/*  ww  w  . j  a v  a2 s .c  o  m*/

    try {
        connection = manager.getConnection();
        connection.setAutoCommit(false);
        st = connection.createStatement();

        // create the database table and populate it with data.
        st.executeUpdate("DROP TABLE IF EXISTS " + tableName);
        st.executeUpdate("CREATE TABLE " + tableName + " (" + manager.escapeColName("id")
                + " INT NOT NULL PRIMARY KEY, " + manager.escapeColName("name") + " VARCHAR(24) NOT NULL, "
                + manager.escapeColName("start_date") + " DATE, " + manager.escapeColName("Salary") + " FLOAT, "
                + manager.escapeColName("dept") + " VARCHAR(32));");

        st.executeUpdate(
                "INSERT INTO " + tableName + " VALUES(1,'Aaron','2009-05-14'," + "1000000.00,'engineering');");
        st.executeUpdate("INSERT INTO " + tableName + " VALUES(2,'Bob','2009-04-20',400.00,'sales');");
        st.executeUpdate("INSERT INTO " + tableName + " VALUES(3,'Fred','2009-01-23'," + "15.00,'marketing');");
        if (nullEntry) {
            st.executeUpdate("INSERT INTO " + tableName + " VALUES(4,'Mike',NULL,NULL,NULL);");
        }

        connection.commit();
    } catch (SQLException sqlE) {
        LOG.error("Encountered SQL Exception: " + sqlE);
        sqlE.printStackTrace();
        fail("SQLException when running test setUp(): " + sqlE);
    } finally {
        try {
            if (null != st) {
                st.close();
            }

            if (null != connection) {
                connection.close();
            }
        } catch (SQLException sqlE) {
            LOG.warn("Got SQLException when closing connection: " + sqlE);
        }
    }
}

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

public ArrayList<String> getUsr(int memberId) {
    ArrayList<String> returnArray = new ArrayList<String>();
    String usr = "";
    String ms = "false";
    connection = DbUtil.getConnection();
    try {/* www.  java2 s. co m*/
        PreparedStatement preparedStatement = connection
                .prepareStatement("SELECT eMail FROM mitglieder WHERE Id = ?");
        preparedStatement.setInt(1, memberId);
        ResultSet rs = preparedStatement.executeQuery();
        if (rs.next()) {
            usr = rs.getString("eMail");
        }
        DbUtil.closeResultSet(rs);
        DbUtil.closePreparedStatement(preparedStatement);
    } catch (SQLException e) {
        e.printStackTrace();
    } finally {
        DbUtil.closeConnection(connection);
    }
    returnArray.add(usr);
    returnArray.add(ms);
    return returnArray;
}

From source file:com.jjtree.servelet.Accounts.java

/**
 * Handles the HTTP <code>POST</code> method.
 *
 * @param request servlet request//from   w  w w .j  ava2  s .  co m
 * @param response servlet response
 * @throws ServletException if a servlet-specific error occurs
 * @throws IOException if an I/O error occurs
 */
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    processRequest(request, response);

    JSONObject jsonObject = JConverter.convert(request);
    if (jsonObject == null) {
        return;
    }

    String account = null;
    String password = null;
    String name = null;
    try {
        account = jsonObject.getString("account");
        name = jsonObject.getString("name");
        password = jsonObject.getString("password");

        if (account == null || password == null || name == null) {
            return;
        }
    } catch (JSONException ex) {
        Logger.getLogger(Accounts.class.getName()).log(Level.SEVERE, null, ex);
    }

    try {

        // Register JDBC driver
        Class.forName(JConstant.JDBC_DRIVER);

        // Open a connection
        conn = DriverManager.getConnection(JConstant.DB_URL, JConstant.USER, JConstant.PASSWORD);

        // Execute SQL query
        stmt = conn.createStatement();

        String sql = "SELECT MAX(userID) FROM JUser";
        ResultSet rs = stmt.executeQuery(sql);

        int nextUserID = 0;
        // Extract data from result set
        while (rs.next()) {
            nextUserID = rs.getInt(1) + 1;
        }

        String insertSql = null;
        if (JString.isEmail(account)) {
            insertSql = "INSERT INTO JUser(email, password, name, userID) VALUES ('" + account + "', '"
                    + password + "', '" + name + "', " + nextUserID + ")";
        }

        if (JString.isPhoneNumber(account)) {
            insertSql = "INSERT INTO JUser(mobile, password, name, userID) VALUES ('" + account + "', '"
                    + password + "', '" + name + "', " + nextUserID + ")";
        }

        Statement stmt2 = conn.createStatement();
        stmt2.executeUpdate(insertSql);

        String accountUrl = "/accounts/" + nextUserID;

        JSONObject accountObject = JServeletManager.fetchFrom(request, accountUrl);

        PrintWriter writer = response.getWriter();
        writer.print(accountObject);
        writer.flush();

        // Clean-up environment
        rs.close();
        stmt.close();
        conn.close();
    } catch (SQLException se) {
        //Handle errors for JDBC
        se.printStackTrace();
    } catch (Exception e) {
        //Handle errors for Class.forName
        e.printStackTrace();
    } finally {
        //finally block used to close resources
        try {
            if (stmt != null) {
                stmt.close();
            }
        } catch (SQLException se2) {
        } // nothing we can do
        try {
            if (conn != null) {
                conn.close();
            }
        } catch (SQLException se) {
            se.printStackTrace();
        } //end finally try
    } //end try
}

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

public void addUser(User user) {
    try {//from  w  w w.  ja  v  a2  s  . c  o m
        PreparedStatement preparedStatement = connection.prepareStatement("INSERT into mitglieder("
                + "Vorname,Nachname,eMail,Telefon,Handy,TelefonDienstlich,Geburtstag,Mitgliedschaft,Stimmrecht,Jugend,AHK,Sonderstatus,eMailDienstlich,gueltig_von,gueltig_bis) "
                + "values (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ? )");
        // Parameters start with 1
        preparedStatement.setString(1, user.getFirstName());
        preparedStatement.setString(2, user.getLastName());
        preparedStatement.setString(3, user.getEmail());
        preparedStatement.setString(4, user.getTelephone());
        preparedStatement.setString(5, user.getHandy());
        preparedStatement.setString(6, user.getPhoneOffice());
        preparedStatement.setString(7, user.getBirthday());
        preparedStatement.setString(8, user.getMembership());
        preparedStatement.setBoolean(9, user.isVoting());
        preparedStatement.setBoolean(10, user.getYouth());
        preparedStatement.setBoolean(11, user.isAhk());
        preparedStatement.setString(12, user.getSpecialStatus());
        preparedStatement.setString(13, user.getEmailOffice());
        preparedStatement.setString(14, user.getMedFrom());
        preparedStatement.setString(15, user.getMedTo());
        preparedStatement.executeUpdate();

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

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

public User getUserById(int userId) {
    connection = DbUtil.getConnection();
    User user = new User();
    try {/*w  ww  .  j  a  v  a2s .c om*/
        PreparedStatement preparedStatement = connection.prepareStatement(
                "SELECT * FROM mitglieder JOIN authentifizierung ON mitglieder.Id = authentifizierung.AuthentId WHERE Id=?");
        preparedStatement.setInt(1, userId);
        ResultSet rs = preparedStatement.executeQuery();

        if (rs.next()) {
            user.setUserid(rs.getInt("Id"));
            user.setFirstName(rs.getString("Vorname"));
            user.setLastName(rs.getString("Nachname"));
            user.setEmail(rs.getString("eMail"));
            user.setTelephone(rs.getString("Telefon"));
            user.setPwd(rs.getString("pwd"));
        }
        DbUtil.closeResultSet(rs);
        DbUtil.closePreparedStatement(preparedStatement);
    } catch (SQLException e) {
        e.printStackTrace();
    } finally {
        DbUtil.closeConnection(connection);
    }

    return user;
}

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

public List<Event> getSchedulerEvents(String start, String end) {
    connection = DbUtil.getConnection();
    List<Event> events = new ArrayList<Event>();
    try {// w ww. j  a v a 2 s.co m
        //            PreparedStatement preparedStatement = connection.prepareStatement("SELECT * FROM events JOIN mitglieder ON events.mitgliederId = mitglieder.id WHERE NOT ((end <= ?) OR (start >= ?))");
        PreparedStatement preparedStatement = connection.prepareStatement(
                "SELECT * FROM events JOIN mitglieder ON mitglieder.Id = events.mitgliederId  WHERE NOT ((events.end <= ?) OR (events.start >= ?))");
        preparedStatement.setString(1, start);
        preparedStatement.setString(2, end);
        ResultSet rs = preparedStatement.executeQuery();
        while (rs.next()) {
            Event event = new Event();
            String startString = formatDateTimeToISO(rs.getString("start"));
            String endString = formatDateTimeToISO(rs.getString("end"));
            event.setId(rs.getInt("id"));
            event.setMitgliederId(rs.getInt("mitgliederId"));
            event.setName(rs.getString("Nachname"));
            event.setStart(startString);
            event.setEnd(endString);
            events.add(event);
        }
    } catch (SQLException e) {
        e.printStackTrace();
    } finally {
        DbUtil.closeConnection(connection);
    }
    return events;
}

From source file:com.extrahardmode.module.MsgPersistModule.java

/**
 * Get the id of the Player. Buffers id in a Map. Creates new id if Player not in the db yet.
 *
 * @param playerName name of the Player//  w  w w .j  a va2 s  .c o  m
 *
 * @return id of Player
 */
private int getPlayerId(String playerName) {
    if (playerIdBuffer.containsKey(playerName))
        return playerIdBuffer.get(playerName);
    int id = 0;

    Connection conn = null;
    Statement aStatement = null;
    ResultSet resultSet = null;
    try {
        conn = retrieveConnection();
        aStatement = conn.createStatement();
        String playerIdQuery = String.format("SELECT id FROM %s WHERE %s = %s", playerTable, "name",
                '"' + playerName + '"');

        resultSet = aStatement.executeQuery(playerIdQuery);
        if (resultSet.next())
            id = resultSet.getInt("id");

        if (id == 0) //Create a new Player
        {
            String newPlayerQuery = String.format( //new id
                    "INSERT INTO %s (%s) VALUES (%s)", playerTable, "name", '"' + playerName + '"');
            aStatement.executeUpdate(newPlayerQuery);

            //Get the id of the just inserted row, I tried getGeneratedKeys() but that wasn't supported by jdbc
            resultSet = aStatement.executeQuery(playerIdQuery);
            if (resultSet.next())
                id = resultSet.getInt("id");

            String newPlayerDataQuery = String.format( //empty row in messages
                    "INSERT INTO %s (%s) VALUES (%s)", msgTable, "id", id);
            aStatement.executeUpdate(newPlayerDataQuery);
            aStatement.close();
        }

        playerIdBuffer.put(playerName, id);
    } catch (SQLException e) {
        e.printStackTrace();
    } finally {
        try {
            if (conn != null)
                conn.close();
            if (aStatement != null)
                aStatement.close();
            if (resultSet != null)
                resultSet.close();
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    return id;
}

From source file:com.sun.licenseserver.License.java

public void addToDatabase() throws LicenseServerException {
    m_log.finer("Entering Function...");
    if (id != null && !"".equals(id.trim())) {
        m_log.severe("Trying to add an already existing license to the database");
        throw new LicenseServerException(LicenseServerException.EC_NO_ERROR_CODE,
                "Trying to add an already existing license to the database");
    }/*from  w w w.j  av  a2 s.  co  m*/
    verifyLicenseFields();
    id = String.valueOf(System.currentTimeMillis());
    m_log.fine("Adding to database a license bject with id=[" + id + "]&shopId=[" + shopId + "]&contentId=["
            + contentId + "]&userId=[" + userId + "]&license=[" + license + "]");
    String sql = "insert into sunLsLicenses (id, contentId, shopId, userId, mime, license) values" + "(" + "'"
            + id + "', " + "'" + contentId + "', " + "'" + shopId + "', " + "'" + userId + "', " + "'" + mime
            + "', " + "?" + ")";
    DatabaseHelper dh = DatabaseHelper.getDatabaseHelper();
    PreparedStatement ps = null;
    Connection con = null;
    con = dh.getConnection();
    try {
        ps = con.prepareStatement(sql);
        ps.setBinaryStream(1, license, (int) licSize);
        ps.executeUpdate();
    } catch (SQLException e) {
        e.printStackTrace();
        new LicenseServerException(LicenseServerException.EC_DATABASE_ERROR,
                "Error in executing the SQL statement to add a license");
    }
    m_log.finer("Leaving Function...");
    return;
}

From source file:com.extrahardmode.module.MsgPersistModule.java

/** Creates tables if they do not exist. */
private void initializeTables() {
    Connection conn = null;// w ww  . j  av a 2  s .c o m
    Statement statement = null;
    try {
        conn = retrieveConnection();
        statement = conn.createStatement();
        statement.setQueryTimeout(30);

        //One table holding the playername id relation
        String playerQuery = String.format(
                "CREATE TABLE IF NOT EXISTS %s (id INTEGER PRIMARY KEY AUTOINCREMENT, %s STRING)", playerTable,
                "name");
        statement.executeUpdate(playerQuery);

        //One column for every message
        StringBuilder columns = new StringBuilder();
        for (MessageNode node : MessageNode.getMessageNodes()) {
            MsgCategory cat = messages.getCat(node);
            if (node.getColumnName() != null && (cat == MsgCategory.TUTORIAL || cat == MsgCategory.ONE_TIME)) {
                columns.append(',');
                columns.append(node.getColumnName());
            }
        }

        String msgQuery = String.format("CREATE TABLE IF NOT EXISTS %s (id INTEGER PRIMARY KEY UNIQUE %s)",
                msgTable, columns);
        statement.executeUpdate(msgQuery);

        //Check if all columns are present
        DatabaseMetaData dmd = conn.getMetaData();
        //Add missing columns
        for (MessageNode node : MessageNode.getMessageNodes()) {
            MsgCategory cat = messages.getCat(node);
            if (cat == MsgCategory.TUTORIAL || cat == MsgCategory.ONE_TIME) {
                ResultSet set = dmd.getColumns(null, null, msgTable, node.getColumnName());
                if (!set.next()) {
                    String updateQuery = String.format("ALTER TABLE %s ADD COLUMN %s", msgTable,
                            node.getColumnName());
                    statement.executeUpdate(updateQuery);
                }
            }
        }
    } catch (SQLException e) {
        e.printStackTrace();
    } finally {
        try {
            if (conn != null)
                conn.close();
            if (statement != null)
                statement.close();
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
}