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:TestDB.java

 public static void main(String args[])
{
   try// w w w .jav  a2  s  .co  m
   {
      runTest();
   }
   catch (SQLException ex)
   {
      for (Throwable t : ex)
         t.printStackTrace();
   }
   catch (IOException ex)
   {
      ex.printStackTrace();
   }
}

From source file:Main.java

public static void main(String[] args) throws Exception {
    String url = "jdbc:mysql://localhost/testdb";
    String username = "root";
    String password = "";
    Class.forName("com.mysql.jdbc.Driver");
    Connection conn = null;//from  w  w w. j  av a  2 s. c om
    try {
        conn = DriverManager.getConnection(url, username, password);
        conn.setAutoCommit(false);

        Statement st = conn.createStatement();
        st.execute("INSERT INTO orders (username, order_date) VALUES ('java', '2007-12-13')",
                Statement.RETURN_GENERATED_KEYS);

        ResultSet keys = st.getGeneratedKeys();
        int id = 1;
        while (keys.next()) {
            id = keys.getInt(1);
        }
        PreparedStatement pst = conn.prepareStatement(
                "INSERT INTO order_details (order_id, product_id, quantity, price) VALUES (?, ?, ?, ?)");
        pst.setInt(1, id);
        pst.setString(2, "1");
        pst.setInt(3, 10);
        pst.setDouble(4, 100);
        pst.execute();

        conn.commit();
        System.out.println("Transaction commit...");
    } catch (SQLException e) {
        if (conn != null) {
            conn.rollback();
            System.out.println("Connection rollback...");
        }
        e.printStackTrace();
    } finally {
        if (conn != null && !conn.isClosed()) {
            conn.close();
        }
    }
}

From source file:edu.lternet.pasta.dml.database.pooling.PostgresDatabaseConnectionPool.java

public static void main(String arg[]) {
    PostgresDatabaseConnectionPool pool = new PostgresDatabaseConnectionPool();
    try {// ww  w  .  j ava2 s .c  o m
        Connection conn = pool.getConnection();
        log.debug("conn=" + conn);
        conn.close();
    } catch (SQLException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (ConnectionNotAvailableException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
}

From source file:com.jt.dbcp.example.BasicDataSourceExample.java

public static void main(String[] args) {
    // First we set up the BasicDataSource.
    // Normally this would be handled auto-magically by
    // an external configuration, but in this example we'll
    // do it manually.
    ////w  ww  .  j av a  2  s . c o m
    String param1 = null;
    String param2 = null;
    if (args.length == 2) {
        param1 = args[0];
        param2 = args[1];
    }

    if (param1 == null) {
        param1 = "jdbc:mysql://localhost:3306/test";
        param2 = "select * from t_user";
    }
    System.out.println("Setting up data source.");
    DataSource dataSource = setupDataSource(param1);
    System.out.println("Done.");

    //
    // Now, we can use JDBC DataSource as we normally would.
    //
    Connection conn = null;
    Statement stmt = null;
    ResultSet rset = null;

    try {
        System.out.println("Creating connection.");
        conn = dataSource.getConnection();
        System.out.println("Creating statement.");
        stmt = conn.createStatement();
        System.out.println("Executing statement.");
        rset = stmt.executeQuery(param2);
        System.out.println("Results:");
        int numcols = rset.getMetaData().getColumnCount();
        int count = 0;
        while (rset.next()) {
            for (int i = 1; i <= numcols; i++) {
                System.out.print("\t" + rset.getString(i));
            }
            System.out.println("");
            count++;
            if (count == 10) {
                break;
            }
        }
        printDataSourceStats(dataSource);

    } catch (SQLException e) {
        e.printStackTrace();
    } finally {
        try {
            if (rset != null)
                rset.close();
        } catch (Exception e) {
        }
        try {
            if (stmt != null)
                stmt.close();
        } catch (Exception e) {
        }
        try {
            if (conn != null)
                conn.close();
        } catch (Exception e) {
        }
        try {
            shutdownDataSource(dataSource);
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
}

From source file:dev.utils.db.dbcp.ManualPoolingDataSource.java

public static void main(String[] args) {

    ////from  w w  w . j av a 2s .  c o m
    // Now, we can use JDBC DataSource as we normally would.
    //
    Connection conn = null;
    Statement stmt = null;
    ResultSet rset = null;

    try {
        System.out.println("Creating connection.");
        //conn = dataSource.getConnection();
        System.out.println("Creating statement.");
        stmt = conn.createStatement();
        System.out.println("Executing statement.");
        rset = stmt.executeQuery(args[1]);
        System.out.println("Results:");
        int numcols = rset.getMetaData().getColumnCount();
        while (rset.next()) {
            for (int i = 1; i <= numcols; i++) {
                System.out.print("\t" + rset.getString(i));
            }
            System.out.println("");
        }
    } catch (SQLException e) {
        e.printStackTrace();
    } finally {
        try {
            rset.close();
        } catch (Exception e) {
        }
        try {
            stmt.close();
        } catch (Exception e) {
        }
        try {
            conn.close();
        } catch (Exception e) {
        }
    }
}

From source file:gov.nih.nci.migration.MigrationDriver.java

public static void main(String[] args) {

    try {/*from   w  ww  . j  a  v  a  2  s  .co  m*/
        if (args.length > 0) {
            PROPERTIES_FILE_NAME = args[0];
        }

        MigrationDriver migrationDriver = new MigrationDriver();
        migrationDriver.encryptDecryptUserInformation();
        migrationDriver.encryptDecryptApplicationInformation();
    } catch (SQLException e) {
        e.printStackTrace();
    } catch (EncryptionException e) {
        e.printStackTrace();
    }
}

From source file:com.ibm.research.rdf.store.runtime.service.sql.UpdateHelper.java

public static void main(String[] args) {
    String JDBC_URL = "jdbc:db2://localhost:10997/lubm";
    String user = "db2inst1";
    String password = "db2admin";

    String backend = "db2";
    String schema = "db2inst1";
    String store = "lubm_100m_r";
    int lock = 1;
    int dph_size = 11;
    int rph_size = 4;

    String[][] triples = { { "http://usersub1/", "http://testpred1/", "http://userobj1/" },
            { "http://usersub1/", "http://testpred2/", "http://userobj2/" },
            { "http://usersub1/", "http://testpred1/", "userobj3" },
            { "http://usersub2/", "http://testpred2/", "http://userobj2/" },
            { "http://usersub1/", "http://testpred3/", "userobj4" },
            { "http://usersub1/", "http://testpred4/", "userobj4" },
            { "http://usersub2/", "http://testpred8/", "http://userobj2/" },
            { "http://usersub2/", "http://testpred6/", "http://userobj2/" },
            { "http://usersub2/", "http://testpred7/", "http://userobj2/" },
            { "http://usersub1/", "http://testpred5/", "userobj5" },
            { "http://usersub2/", "http://testpred9/", "http://userobj2/" },
            { "http://usersub3/", "http://testpred2/", "http://userobj2/" },
            { "http://usersub1/", "http://testpred1/", "userobj4" },
            { "http://usersub1/", "http://testpred1/", "userobj5" },
            { "http://usersub1/", "http://testpred3/", "userobj5" },
            { "http://usersub4/", "http://testpred2/", "http://userobj2/" },
            { "http://usersub3/", "http://testpred1/", "userobj3" } };

    try {//from w w  w.  j  a  v  a 2  s .co m

        String classNameString = new String("com.ibm.db2.jcc.DB2Driver");
        Class.forName(classNameString);

        Connection conn = DriverManager.getConnection(JDBC_URL, user, password);

        String gid = "DEF";

        //add triples to graph DEF
        for (int i = 0; i < triples.length; i++) {
            String sub = triples[i][0];
            String pred = triples[i][1];
            String obj = triples[i][2];
            int obj_dt = obj.startsWith("http://") ? 10002 : 5001;
            int dft_col = i % 2;

            addTriple(conn, backend, schema, store, sub, pred, obj, obj_dt, dft_col, dft_col, gid, lock);
        }

        gid = "G1";

        //add triples to graph G1
        //some operations will fail due to UNIQUE indexes (on DS, RS) without GID
        for (int i = 0; i < triples.length; i++) {
            String sub = triples[i][0];
            String pred = triples[i][1];
            String obj = triples[i][2];
            int obj_dt = obj.startsWith("http://") ? 10002 : 5001;
            int dft_col = i % 2;

            addTriple(conn, backend, schema, store, sub, pred, obj, obj_dt, dft_col, dft_col, gid, lock);
        }

        gid = "DEF";

        //delete triples to graph DEF
        for (int i = triples.length - 1; i >= 0; i--) {
            String sub = triples[i][0];
            String pred = triples[i][1];
            String obj = triples[i][2];
            int dft_col = i % 2;

            deleteTriple(conn, backend, schema, store, sub, pred, obj, dph_size, rph_size, dft_col, dft_col,
                    gid, lock);
        }

        gid = "G1";

        //delete triples to graph G1
        for (int i = triples.length - 1; i >= 0; i--) {
            String sub = triples[i][0];
            String pred = triples[i][1];
            String obj = triples[i][2];
            int dft_col = i % 2;

            deleteTriple(conn, backend, schema, store, sub, pred, obj, dph_size, rph_size, dft_col, dft_col,
                    gid, lock);
        }

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

}

From source file:DeliverWork.java

public static void main(String[] args) throws UnsupportedEncodingException, MessagingException {
    JdbcFactory jdbcFactoryChanye = new JdbcFactory(
            "jdbc:mysql://127.0.0.1:3306/fp_guimin?useUnicode=true&characterEncoding=UTF-8", "guimin_db",
            "guimin@98fhi3p2hUFHfdfoi", "com.mysql.jdbc.Driver");
    connection = jdbcFactoryChanye.getConnection();
    Map<String, String> map = new HashMap();

    try {// w w  w . j a  v  a 2 s  .co m
        PreparedStatement ps = connection.prepareStatement(selectAccount);
        ResultSet resultSet = ps.executeQuery();
        while (resultSet.next()) {
            map.put(resultSet.getString(1), resultSet.getString(2));
        }
        ps.close();
        map.forEach((k, v) -> {
            syncTheFile(k, v);
        });
        connection.close();
    } catch (SQLException e) {
        e.printStackTrace();
    } finally {
        try {
            connection.close();
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
}

From source file:fr.eo.util.dumper.Dumper.java

/**
 * @param args//from  www. ja  va 2 s .co m
 */
public static void main(String[] args) {

    String appName = args[0];

    System.out.println("Starting dumper ...");

    Statement stmt = null;

    try {
        System.out.println("Getting database connection ...");
        Connection conn = getJtdsConnection();

        List<RequestDefinitionBean> requests = RequestDefinitionParser.getRequests(appName);

        assetFolder = RequestDefinitionParser.getAppBaseDir(appName) + "assets/";

        for (RequestDefinitionBean request : requests) {
            int currentFileSize = 0, cpt = 1;
            stmt = conn.createStatement();
            System.out.println("Dumping " + request.name + "...");
            ResultSet rs = stmt.executeQuery(request.sql);
            BufferedWriter bw = getWriter(request.name, cpt);
            bw.append(COPYRIGHTS);
            currentFileSize += COPYRIGHTS.length();
            bw.append("--" + request.name + "\n");
            while (rs.next()) {
                StringBuilder sb = new StringBuilder();
                sb.append("INSERT INTO ");
                sb.append(request.table).append(" VALUES (");
                int pos = 0;
                for (String fieldName : request.fields) {
                    String str = getFieldValue(request, pos, rs, fieldName);
                    sb.append(str);
                    pos++;
                    if (pos < request.fields.size()) {
                        sb.append(",");
                    }
                }
                sb.append(");\n");
                currentFileSize += sb.length();
                bw.append(sb.toString());
                bw.flush();

                if (currentFileSize > MAX_FILE_SIZE) {
                    bw.close();

                    bw = getWriter(request.name, ++cpt);
                    bw.append(COPYRIGHTS);
                    bw.append("--" + request.name + "\n");
                    currentFileSize = COPYRIGHTS.length();
                }
            }
            bw.flush();
            bw.close();
        }

        System.out.println("done.");

    } catch (SQLException e) {
        e.printStackTrace();
    } catch (ClassNotFoundException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        if (stmt != null) {
            try {
                stmt.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }

    DumpFilesDescriptor descriptor = new DumpFilesDescriptor();
    descriptor.lineNumbers = getDumpLinesNumber();
    descriptor.dumpFileNames = dumpFileNames;
    writeDescriptorFile(descriptor);

    System.out.println("nb :" + descriptor.lineNumbers);
}

From source file:jfutbol.com.jfutbol.GcmSender.java

public static void main(String[] args) {
    log.info("GCM - Sender running");
    do {//from w  w  w  .  j  av  a2 s .  co m

        Connection conn = null;
        Connection conn2 = null;
        Statement stmt = null;
        Statement stmt2 = null;

        try {
            // STEP 2: Register JDBC driver
            Class.forName(JDBC_DRIVER);
            // STEP 3: Open a connection
            // System.out.println("Connecting to database...");
            conn = DriverManager.getConnection(DB_URL, USER, PASS);
            conn2 = DriverManager.getConnection(DB_URL, USER, PASS);
            // STEP 4: Execute a query
            // System.out.println("Creating statement...");
            stmt = conn.createStatement();
            String sql;
            sql = "SELECT userId FROM notifications WHERE sentByGCM=0 GROUP BY userId";
            ResultSet rs = stmt.executeQuery(sql);
            // STEP 5: Extract data from result set
            while (rs.next()) {
                log.info("Notification found");
                int userId = rs.getInt("userId");

                stmt2 = conn2.createStatement();
                String sql2;
                sql2 = "SELECT COUNT(id) notificationCounter FROM notifications WHERE status=0 AND userId="
                        + userId;
                ResultSet rs2 = stmt2.executeQuery(sql2);
                int notificationCounter = rs2.getInt("notificationCounter");
                rs2.close();
                stmt2.close();
                // Retrieve by column name

                // Display values
                // System.out.print("userId: " + userId);
                // System.out.print(", notificationCounter: " +
                // notificationCounter);
                SendNotification(userId, notificationCounter);
            }
            // STEP 6: Clean-up environment
            rs.close();
            stmt.close();
            conn.close();
            conn2.close();
        } catch (SQLException se) {
            // Handle errors for JDBC
            log.error(se.getMessage());
            se.printStackTrace();
        } catch (Exception e) {
            // Handle errors for Class.forName
            log.error(e.getMessage());
            e.printStackTrace();
        } finally {
            // finally block used to close resources
            try {
                if (stmt != null)
                    stmt.close();
            } catch (SQLException se2) {
                log.error(se2.getMessage());
            } // nothing we can do
            try {
                if (conn != null)
                    conn.close();
            } catch (SQLException se) {
                log.error(se.getMessage());
                se.printStackTrace();
            } // end finally try
        } // end try
        try {
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            log.error(e.getMessage());
            e.printStackTrace();
        }
    } while (1 != 0);
}