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.jjtree.servelet.Accounts.java

/**
 * Handles the HTTP <code>GET</code> method.
 *
 * @param request servlet request//w w  w . j  a  v  a 2  s .  c  o m
 * @param response servlet response
 * @throws ServletException if a servlet-specific error occurs
 * @throws IOException if an I/O error occurs
 */
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    processRequest(request, response);

    String pathInfo = request.getPathInfo();
    String[] path = pathInfo.split("/");
    int userID = Integer.parseInt(path[1]);

    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;
        sql = "SELECT * FROM JUser WHERE userID = " + userID;
        ResultSet rs = stmt.executeQuery(sql);

        // Extract data from result set
        while (rs.next()) {
            //Retrieve by column name
            int accountID = rs.getInt("userID");

            String email = rs.getString("email");
            String mobile = rs.getString("mobile");
            String password = rs.getString("password");
            String name = rs.getString("name");
            String avatarURL = rs.getString("avatarURL");

            JSONObject account = new JSONObject();

            account.put("accountID", accountID);
            account.put("email", email);
            account.put("mobile", mobile);
            account.put("password", password);
            account.put("name", name);
            account.put("avatarURL", avatarURL);

            PrintWriter writer = response.getWriter();
            writer.print(account);
            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:gr.osmosis.rcpsamples.contact.db.derby.DerbyContactsDAO.java

public boolean dropTable() {

    try {/*w  w  w  . ja v  a2  s.c  o m*/
        StringBuffer sbDrop = new StringBuffer();

        sbDrop.append("DROP TABLE APP.CONTACTS");

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

        run.update(sbDrop.toString());

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

    return true;
}

From source file:my.yelp.populate.java

public Connection getConnection() {
    String JDBC_DRIVER = "oracle.jdbc.driver.OracleDriver";
    String DB_URL = "jdbc:mysql://localhost/";

    Statement stmt = null;/*  ww  w.jav  a2s .c  om*/
    String user = "vishrutshah15";
    String password = "Rutva1526#";
    String port = "1521";
    String DBname = "SYSTEM";
    try {
        Class.forName("oracle.jdbc.driver.OracleDriver");
    } catch (ClassNotFoundException e) {
        System.out.println("Connection failed!" + e);
        return null;
    }
    try {
        //System.out.println("Connecting to database...");
        conn = DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:xe", user, password);
        //System.out.println("Creating database...");
        System.out.println("Database created successfully...");
        return conn;
        //                      

    } catch (SQLException se) {
        System.out.println("Connection failed!" + se);
        se.printStackTrace();
    } catch (Exception e) {

        e.printStackTrace();

    }
    return null;
}

From source file:com.firma.dev.letschat.MyFavoriteFragment.java

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {

    final View listFragmentView = super.onCreateView(inflater, container, savedInstanceState);

    apiManager = new ApiManager();
    ProfileDataSource profileDao = new ProfileDataSource(inflater.getContext());

    try {/*w w  w.  j a va  2s  .  com*/
        profileDao.open();

        currentProfile = profileDao.getAllProfiles().get(0);
        profileDao.close();
    } catch (SQLException e) {
        e.printStackTrace();
    }

    userContactsTimer = new Timer();
    getUserContactsTask = new GetUserContactsTask();

    userContactsTimer.schedule(getUserContactsTask, 1000, 60000);

    fAdapter = new FavoriteAdapter(inflater.getContext(), getActivity());
    setListAdapter(fAdapter);

    mSwipeRefreshLayout = new ListFragmentSwipeRefreshLayout(container.getContext());

    mSwipeRefreshLayout.addView(listFragmentView, ViewGroup.LayoutParams.MATCH_PARENT,
            ViewGroup.LayoutParams.MATCH_PARENT);

    mSwipeRefreshLayout.setLayoutParams(new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,
            ViewGroup.LayoutParams.MATCH_PARENT));

    this.setRefreshing(false);

    mSwipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
        @Override
        public void onRefresh() {
            forceUpdate();
        }
    });
    return mSwipeRefreshLayout;
}

From source file:edu.lternet.pasta.portal.statistics.GrowthStats.java

public String getGoogleChartJson(GregorianCalendar now, int scale) {

    StringBuilder pkgSql = new StringBuilder();
    pkgSql.append("SELECT scope || '.' || identifier,date_created FROM ");
    pkgSql.append(RESOURCE_REGISTRY);/*  w  ww  . jav  a  2 s  .  c o  m*/
    pkgSql.append(" WHERE resource_type='dataPackage' AND ");
    pkgSql.append("date_deactivated IS NULL AND ");
    pkgSql.append("scope LIKE 'knb-lter-%' AND NOT scope='knb-lter-nwk' ");
    pkgSql.append("ORDER BY date_created ASC;");

    HashMap<String, Long> pkgMap;

    try {
        pkgMap = buildHashMap(pkgSql.toString());
    } catch (SQLException e) {
        logger.error("getGoogleChartJson: " + e.getMessage());
        e.printStackTrace();
        pkgMap = new HashMap<String, Long>(); // Create empty package map
    }

    Long[] pkgList = buildSortedList(pkgMap);

    StringBuilder siteSql = new StringBuilder();
    siteSql.append("SELECT scope,date_created FROM ");
    siteSql.append(RESOURCE_REGISTRY);
    siteSql.append(" WHERE resource_type='dataPackage' AND ");
    siteSql.append("date_deactivated IS NULL AND ");
    siteSql.append("scope LIKE 'knb-lter-%' AND NOT scope='knb-lter-nwk' ");
    siteSql.append("ORDER BY date_created ASC;");

    HashMap<String, Long> siteMap = null;
    try {
        siteMap = buildHashMap(siteSql.toString());
    } catch (SQLException e) {
        logger.error("getGoogleChartJson: " + e.getMessage());
        e.printStackTrace();
        siteMap = new HashMap<String, Long>(); // Create empty site map
    }

    Long[] siteList = buildSortedList(siteMap);

    ArrayList<String> labels = buildLabels(origin, now, scale);
    ArrayList<Integer> pkgFreq = buildFrequencies(origin, now, scale, pkgList);
    ArrayList<Integer> siteFreq = buildFrequencies(origin, now, scale, siteList);

    Integer pkgCDist = 0;
    Integer siteCDist = 0;
    int i;

    StringBuilder json = new StringBuilder();

    for (i = 0; i < labels.size() - 1; i++) {
        pkgCDist += pkgFreq.get(i);
        siteCDist += siteFreq.get(i);
        json.append(String.format("['%s',%d,%d],%n", labels.get(i), pkgCDist, siteCDist));
    }

    i = labels.size() - 1;
    pkgCDist += pkgFreq.get(i);
    siteCDist += siteFreq.get(i);
    json.append(String.format("['%s',%d,%d]%n", labels.get(i), pkgCDist, siteCDist));

    return json.toString();

}

From source file:com.cloudera.sqoop.manager.PostgresqlTest.java

@Before
public void setUp() {
    super.setUp();

    LOG.debug("Setting up another postgresql test: " + CONNECT_STRING);

    SqoopOptions options = new SqoopOptions(CONNECT_STRING, TABLE_NAME);
    options.setUsername(DATABASE_USER);// ww  w .  j  av a 2s .  c o  m

    ConnManager manager = null;
    Connection connection = null;
    Statement st = null;

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

        // create the database table and populate it with data.

        try {
            // Try to remove the table first. DROP TABLE IF EXISTS didn't
            // get added until pg 8.3, so we just use "DROP TABLE" and ignore
            // any exception here if one occurs.
            st.executeUpdate("DROP TABLE " + TABLE_NAME);
        } catch (SQLException e) {
            LOG.info("Couldn't drop table " + TABLE_NAME + " (ok)");
            LOG.info(e.toString());
            // Now we need to reset the transaction.
            connection.rollback();
        }

        st.executeUpdate("CREATE TABLE " + TABLE_NAME + " (" + "id INT NOT NULL PRIMARY KEY, "
                + "name VARCHAR(24) NOT NULL, " + "start_date DATE, " + "salary FLOAT, " + "dept VARCHAR(32))");

        st.executeUpdate(
                "INSERT INTO " + TABLE_NAME + " VALUES(" + "1,'Aaron','2009-05-14',1000000.00,'engineering')");
        st.executeUpdate("INSERT INTO " + TABLE_NAME + " VALUES(" + "2,'Bob','2009-04-20',400.00,'sales')");
        st.executeUpdate("INSERT INTO " + TABLE_NAME + " VALUES(" + "3,'Fred','2009-01-23',15.00,'marketing')");
        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 != manager) {
                manager.close();
            }
        } catch (SQLException sqlE) {
            LOG.warn("Got SQLException when closing connection: " + sqlE);
        }
    }

    LOG.debug("setUp complete.");
}

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

public void deleteUser(int userId) {
    try {/*from   www  .  j a v a  2  s .co  m*/
        PreparedStatement preparedStatement = connection.prepareStatement("DELETE from mitglieder where Id=?");
        // Parameters start with 1
        preparedStatement.setInt(1, userId);
        preparedStatement.executeUpdate();

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

From source file:azkaban.migration.scheduler.JdbcScheduleLoader.java

@Override
public void updateNextExecTime(Schedule s) throws ScheduleManagerException {
    logger.info("Update schedule " + s.getScheduleName() + " into db. ");
    Connection connection = getConnection();
    QueryRunner runner = new QueryRunner();
    try {/*from   w w w  .  j av a 2  s  .  c o  m*/

        runner.update(connection, UPDATE_NEXT_EXEC_TIME, s.getNextExecTime(), s.getProjectId(),
                s.getFlowName());
    } catch (SQLException e) {
        e.printStackTrace();
        logger.error(UPDATE_NEXT_EXEC_TIME + " failed.", e);
        throw new ScheduleManagerException("Update schedule " + s.getScheduleName() + " into db failed. ", e);
    } finally {
        DbUtils.closeQuietly(connection);
    }
}

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

/**
 * Get how often a message has been displayed
 *
 * @param node     to get the count for//from w  ww  .  j a v  a  2s . co m
 * @param playerId id of the player to get the count for
 *
 * @return how often this message has been displayed
 */
private int getCountFor(MessageNode node, int playerId) {
    Connection conn = null;
    Statement statement = null;
    ResultSet result = null;
    int value = 0;

    try {
        conn = retrieveConnection();
        statement = conn.createStatement();

        String select = String.format("SELECT * FROM %s WHERE %s = %s", msgTable, "id", playerId);

        result = statement.executeQuery(select);
        if (result.next())
            value = result.getInt(node.getColumnName());
        else //create the missing row
        {
            String newPlayerDataQuery = String.format( //empty row in messages
                    "INSERT INTO %s (%s) VALUES (%s)", msgTable, "id", playerId);
            conn.createStatement().executeUpdate(newPlayerDataQuery);
        }
    } catch (SQLException e) {
        e.printStackTrace();
    } finally {
        try {
            if (conn != null)
                conn.close();
            if (statement != null)
                statement.close();
            if (result != null)
                result.close();
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    return value;
}

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

public boolean createTable() {

    try {//from  w w w  . j ava  2  s.  co m
        StringBuffer sbCreate = new StringBuffer();

        sbCreate.append("CREATE TABLE APP.CONTACTS (");
        sbCreate.append("ID INTEGER NOT NULL GENERATED ALWAYS AS IDENTITY (START WITH 1, INCREMENT BY 1),");
        sbCreate.append("FNAME VARCHAR(30), ");
        sbCreate.append("LNAME VARCHAR(30),");
        sbCreate.append("PHONE VARCHAR(30),");
        sbCreate.append("ADDRESS VARCHAR(30),");
        sbCreate.append("CITY VARCHAR(30),");
        sbCreate.append("ZIP VARCHAR(30),");
        sbCreate.append("PRIMARY KEY(ID) )");

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

        run.update(sbCreate.toString());

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

    return true;
}