Example usage for java.sql ResultSet next

List of usage examples for java.sql ResultSet next

Introduction

In this page you can find the example usage for java.sql ResultSet next.

Prototype

boolean next() throws SQLException;

Source Link

Document

Moves the cursor forward one row from its current position.

Usage

From source file:InsertRows.java

public static void main(String args[]) {

    String url = "jdbc:mySubprotocol:myDataSource";
    Connection con;/* ww  w  . ja v a  2s.com*/
    Statement stmt;
    try {
        Class.forName("myDriver.ClassName");

    } catch (java.lang.ClassNotFoundException e) {
        System.err.print("ClassNotFoundException: ");
        System.err.println(e.getMessage());
    }

    try {

        con = DriverManager.getConnection(url, "myLogin", "myPassword");

        stmt = con.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_UPDATABLE);

        ResultSet uprs = stmt.executeQuery("SELECT * FROM COFFEES");

        uprs.moveToInsertRow();

        uprs.updateString("COF_NAME", "Kona");
        uprs.updateInt("SUP_ID", 150);
        uprs.updateFloat("PRICE", 10.99f);
        uprs.updateInt("SALES", 0);
        uprs.updateInt("TOTAL", 0);

        uprs.insertRow();

        uprs.updateString("COF_NAME", "Kona_Decaf");
        uprs.updateInt("SUP_ID", 150);
        uprs.updateFloat("PRICE", 11.99f);
        uprs.updateInt("SALES", 0);
        uprs.updateInt("TOTAL", 0);

        uprs.insertRow();

        uprs.beforeFirst();

        System.out.println("Table COFFEES after insertion:");
        while (uprs.next()) {
            String name = uprs.getString("COF_NAME");
            int id = uprs.getInt("SUP_ID");
            float price = uprs.getFloat("PRICE");
            int sales = uprs.getInt("SALES");
            int total = uprs.getInt("TOTAL");
            System.out.print(name + "   " + id + "   " + price);
            System.out.println("   " + sales + "   " + total);
        }

        uprs.close();
        stmt.close();
        con.close();

    } catch (SQLException ex) {
        System.err.println("SQLException: " + ex.getMessage());
    }
}

From source file:com.mycompany.mavenproject4.web.java

/**
 * @param args the command line arguments
 *//*from w w  w. ja va2 s. c  o  m*/
public static void main(String[] args) {
    System.out.println("Enter your choice do you want to work with \n 1.PostGreSQL \n 2.Redis \n 3.Mongodb");
    InputStreamReader IORdatabase = new InputStreamReader(System.in);
    BufferedReader BIOdatabase = new BufferedReader(IORdatabase);
    String Str1 = null;
    try {
        Str1 = BIOdatabase.readLine();
    } catch (Exception E7) {
        System.out.println(E7.getMessage());
    }

    // loading data from the CSV file 

    CsvReader data = null;

    try {
        data = new CsvReader("\\data\\Consumer_Complaints.csv");
    } catch (FileNotFoundException EB) {
        System.out.println(EB.getMessage());
    }
    int noofcolumn = 5;
    int noofrows = 100;
    int loops = 0;

    try {
        data = new CsvReader("\\data\\Consumer_Complaints.csv");
    } catch (FileNotFoundException E) {
        System.out.println(E.getMessage());
    }

    String[][] Dataarray = new String[noofrows][noofcolumn];
    try {
        while (data.readRecord()) {
            String v;
            String[] x;
            v = data.getRawRecord();
            x = v.split(",");
            for (int j = 0; j < noofcolumn; j++) {
                String value = null;
                int z = j;
                value = x[z];
                try {
                    Dataarray[loops][j] = value;
                } catch (Exception E) {
                    System.out.println(E.getMessage());
                }
                // System.out.println(Dataarray[iloop][j]);
            }
            loops = loops + 1;
        }
    } catch (IOException Em) {
        System.out.println(Em.getMessage());
    }

    data.close();

    // connection to Database 
    switch (Str1) {
    // postgre code goes here 
    case "1":

        Connection Conn = null;
        Statement Stmt = null;
        URI dbUri = null;
        String choice = null;
        InputStreamReader objin = new InputStreamReader(System.in);
        BufferedReader objbuf = new BufferedReader(objin);
        try {
            Class.forName("org.postgresql.Driver");
        } catch (Exception E1) {
            System.out.println(E1.getMessage());
        }
        String username = "ahkyjdavhedkzg";
        String password = "2f7c3_MBJbIy1uJsFyn7zebkhY";
        String dbUrl = "jdbc:postgresql://ec2-54-83-199-54.compute-1.amazonaws.com:5432/d2l6hq915lp9vi?ssl=true&sslfactory=org.postgresql.ssl.NonValidatingFactory";

        // now update data in the postgress Database 

        /*  for(int i=0;i<RowCount;i++)
           {
                try 
        {
                          
        Conn= DriverManager.getConnection(dbUrl, username, password);    
        Stmt = Conn.createStatement();
                  String Connection_String = "insert into Webdata (Id,Product,state,Submitted,Complaintid) values (' "+ Dataarray[i][0]+" ',' "+ Dataarray[i][1]+" ',' "+ Dataarray[i][2]+" ',' "+ Dataarray[i][3]+" ',' "+ Dataarray[i][4]+" ')";
         Stmt.executeUpdate(Connection_String);
                  Conn.close();
        }
        catch(SQLException E4)
                  {
           System.out.println(E4.getMessage());
        }
           }
           */
        // Quering with the Database 

        System.out.println("1. Display Data ");
        System.out.println("2. Select data based on primary key");
        System.out.println("3. Select data based on Other attributes e.g Name");
        System.out.println("Enter your Choice ");
        try {
            choice = objbuf.readLine();
        } catch (IOException E) {
            System.out.println(E.getMessage());
        }
        switch (choice) {
        case "1":
            try {
                Conn = DriverManager.getConnection(dbUrl, username, password);
                Stmt = Conn.createStatement();
                String Connection_String = " Select * from Webdata;";
                ResultSet objRS = Stmt.executeQuery(Connection_String);
                while (objRS.next()) {
                    System.out.println(" ID: " + objRS.getInt("ID"));
                    System.out.println("Product Name: " + objRS.getString("Product"));
                    System.out.println("Which state: " + objRS.getString("State"));
                    System.out.println("Sumbitted through: " + objRS.getString("Submitted"));
                    System.out.println("Complain Number: " + objRS.getString("Complaintid"));
                    Conn.close();
                }

            } catch (Exception E2) {
                System.out.println(E2.getMessage());
            }

            break;

        case "2":

            System.out.println("Enter Id(Primary Key) :");
            InputStreamReader objkey = new InputStreamReader(System.in);
            BufferedReader objbufkey = new BufferedReader(objkey);
            int key = 0;
            try {
                key = Integer.parseInt(objbufkey.readLine());
            } catch (IOException E) {
                System.out.println(E.getMessage());
            }
            try {
                Conn = DriverManager.getConnection(dbUrl, username, password);
                Stmt = Conn.createStatement();
                String Connection_String = " Select * from Webdata where Id=" + key + ";";
                ResultSet objRS = Stmt.executeQuery(Connection_String);
                while (objRS.next()) {
                    //System.out.println(" ID: " + objRS.getInt("ID"));
                    System.out.println("Product Name: " + objRS.getString("Product"));
                    System.out.println("Which state: " + objRS.getString("State"));
                    System.out.println("Sumbitted through: " + objRS.getString("Submitted"));
                    System.out.println("Complain Number: " + objRS.getString("Complaintid"));
                    Conn.close();
                }

            } catch (Exception E2) {
                System.out.println(E2.getMessage());
            }
            break;

        case "3":
            //String Name=null;
            System.out.println("Enter Complaintid to find the record");

            // Scanner input = new Scanner(System.in);
            //
            int Number = 0;
            try {
                InputStreamReader objname = new InputStreamReader(System.in);
                BufferedReader objbufname = new BufferedReader(objname);

                Number = Integer.parseInt(objbufname.readLine());
            } catch (Exception E10) {
                System.out.println(E10.getMessage());
            }
            //System.out.println(Name);
            try {
                Conn = DriverManager.getConnection(dbUrl, username, password);
                Stmt = Conn.createStatement();
                String Connection_String = " Select * from Webdata where complaintid=" + Number + ";";
                //2
                System.out.println(Connection_String);
                ResultSet objRS = Stmt.executeQuery(Connection_String);
                while (objRS.next()) {
                    int id = objRS.getInt("id");
                    System.out.println(" ID: " + id);
                    System.out.println("Product Name: " + objRS.getString("Product"));
                    String state = objRS.getString("state");
                    System.out.println("Which state: " + state);
                    String Submitted = objRS.getString("submitted");
                    System.out.println("Sumbitted through: " + Submitted);
                    String Complaintid = objRS.getString("complaintid");
                    System.out.println("Complain Number: " + Complaintid);

                }
                Conn.close();
            } catch (Exception E2) {
                System.out.println(E2.getMessage());
            }
            break;
        }
        try {
            Conn.close();
        } catch (SQLException E6) {
            System.out.println(E6.getMessage());
        }
        break;

    // Redis code goes here 

    case "2":
        int Length = 0;
        String ID = null;
        Length = 100;

        // Connection to Redis 
        Jedis jedis = new Jedis("pub-redis-13274.us-east-1-2.1.ec2.garantiadata.com", 13274);
        jedis.auth("rfJ8OLjlv9NjRfry");
        System.out.println("Connected to Redis Database");

        // Storing values in the database 

        /* 
        for(int i=0;i<Length;i++)
        { 
         //Store data in redis 
            int j=i+1;
        jedis.hset("Record:" + j , "Product", Dataarray[i][1]);
        jedis.hset("Record:" + j , "State ", Dataarray[i][2]);
        jedis.hset("Record:" + j , "Submitted", Dataarray[i][3]);
        jedis.hset("Record:" + j , "Complaintid", Dataarray[i][4]);
                
        }
        */
        System.out.println(
                "Search by \n 11.Get records through primary key \n 22.Get Records through Complaintid \n 33.Display ");
        InputStreamReader objkey = new InputStreamReader(System.in);
        BufferedReader objbufkey = new BufferedReader(objkey);
        String str2 = null;
        try {
            str2 = objbufkey.readLine();
        } catch (IOException E) {
            System.out.println(E.getMessage());
        }
        switch (str2) {
        case "11":
            System.out.print("Enter Primary Key : ");
            InputStreamReader IORKey = new InputStreamReader(System.in);
            BufferedReader BIORKey = new BufferedReader(IORKey);
            String ID1 = null;
            try {
                ID1 = BIORKey.readLine();
            } catch (IOException E3) {
                System.out.println(E3.getMessage());
            }

            Map<String, String> properties = jedis.hgetAll("Record:" + Integer.parseInt(ID1));
            for (Map.Entry<String, String> entry : properties.entrySet()) {
                System.out.println("Product:" + jedis.hget("Record:" + Integer.parseInt(ID1), "Product"));
                System.out.println("State:" + jedis.hget("Record:" + Integer.parseInt(ID1), "State"));
                System.out.println("Submitted:" + jedis.hget("Record:" + Integer.parseInt(ID1), "Submitted"));
                System.out
                        .println("Complaintid:" + jedis.hget("Record:" + Integer.parseInt(ID1), "Complaintid"));
            }
            break;

        case "22":
            System.out.print(" Enter Complaintid  : ");
            InputStreamReader IORName1 = new InputStreamReader(System.in);
            BufferedReader BIORName1 = new BufferedReader(IORName1);

            String ID2 = null;
            try {
                ID2 = BIORName1.readLine();
            } catch (IOException E3) {
                System.out.println(E3.getMessage());
            }
            for (int i = 0; i < 100; i++) {
                Map<String, String> properties3 = jedis.hgetAll("Record:" + i);
                for (Map.Entry<String, String> entry : properties3.entrySet()) {
                    String value = entry.getValue();
                    if (entry.getValue().equals(ID2)) {
                        System.out
                                .println("Product:" + jedis.hget("Record:" + Integer.parseInt(ID2), "Product"));
                        System.out.println("State:" + jedis.hget("Record:" + Integer.parseInt(ID2), "State"));
                        System.out.println(
                                "Submitted:" + jedis.hget("Record:" + Integer.parseInt(ID2), "Submitted"));
                        System.out.println(
                                "Complaintid:" + jedis.hget("Record:" + Integer.parseInt(ID2), "Complaintid"));
                    }

                }
            }

            break;

        case "33":
            for (int i = 1; i < 21; i++) {
                Map<String, String> properties3 = jedis.hgetAll("Record:" + i);
                for (Map.Entry<String, String> entry : properties3.entrySet()) {

                    System.out.println("Product:" + jedis.hget("Record:" + i, "Product"));
                    System.out.println("State:" + jedis.hget("Record:" + i, "State"));
                    System.out.println("Submitted:" + jedis.hget("Record:" + i, "Submitted"));
                    System.out.println("Complaintid:" + jedis.hget("Record:" + i, "Complaintid"));

                }
            }
            break;
        }

        break;

    // mongo db 

    case "3":
        MongoClient mongo = new MongoClient(new MongoClientURI(
                "mongodb://naikhpratik:naikhpratik@ds053964.mongolab.com:53964/heroku_6t7n587f"));
        DB db;
        db = mongo.getDB("heroku_6t7n587f");
        // storing values in the database 
        /*for(int i=0;i<100;i++)
         {
             BasicDBObject document = new BasicDBObject();
            document.put("Id", i+1);
            document.put("Product", Dataarray[i][1]);
            document.put("State", Dataarray[i][2]);    
            document.put("Submitted", Dataarray[i][3]);    
            document.put("Complaintid", Dataarray[i][4]); 
            db.getCollection("Naiknaik").insert(document);
                  
         }*/
        System.out.println("Search by \n 1.Enter Primary key \n 2.Enter Complaintid \n 3.Display");
        InputStreamReader objkey6 = new InputStreamReader(System.in);
        BufferedReader objbufkey6 = new BufferedReader(objkey6);
        String str3 = null;
        try {
            str3 = objbufkey6.readLine();
        } catch (IOException E) {
            System.out.println(E.getMessage());
        }
        switch (str3) {
        case "1":
            System.out.println("Enter the Primary Key");
            InputStreamReader IORPkey = new InputStreamReader(System.in);
            BufferedReader BIORPkey = new BufferedReader(IORPkey);
            int Pkey = 0;
            try {
                Pkey = Integer.parseInt(BIORPkey.readLine());
            } catch (IOException E) {
                System.out.println(E.getMessage());
            }
            BasicDBObject inQuery = new BasicDBObject();
            inQuery.put("Id", Pkey);
            DBCursor cursor = db.getCollection("Naiknaik").find(inQuery);
            while (cursor.hasNext()) {
                // System.out.println(cursor.next());
                System.out.println(cursor.next());
            }
            break;
        case "2":
            System.out.println("Enter the Product to Search");
            InputStreamReader objName = new InputStreamReader(System.in);
            BufferedReader objbufName = new BufferedReader(objName);
            String Name = null;
            try {
                Name = objbufName.readLine();
            } catch (IOException E) {
                System.out.println(E.getMessage());
            }
            BasicDBObject inQuery1 = new BasicDBObject();
            inQuery1.put("Product", Name);
            DBCursor cursor1 = db.getCollection("Naiknaik").find(inQuery1);
            while (cursor1.hasNext()) {
                // System.out.println(cursor.next());
                System.out.println(cursor1.next());
            }
            break;

        case "3":
            for (int i = 1; i < 21; i++) {
                BasicDBObject inQuerya = new BasicDBObject();
                inQuerya.put("_id", i);
                DBCursor cursora = db.getCollection("Naiknaik").find(inQuerya);
                while (cursora.hasNext()) {
                    // System.out.println(cursor.next());
                    System.out.println(cursora.next());
                }
            }
            break;
        }
        break;

    }

}

From source file:Main.java

public static void main(String[] args) throws Exception {
    String driver = "sun.jdbc.odbc.JdbcOdbcDriver";

    Connection con;//from   ww  w.  j av a2s  .c om
    Statement stmt;
    ResultSet rs;

    try {
        Class.forName(driver);
        con = DriverManager.getConnection("jdbc:odbc:databaseName", "student", "student");
        // Start a transaction
        con.setAutoCommit(false);

        stmt = con.createStatement();
        stmt.addBatch("UPDATE EMP SET JOB = 1");

        // Submit the batch of commands for this statement to the database
        stmt.executeBatch();

        // Commit the transaction
        con.commit();

        // Close the existing to be safe before opening a new one
        stmt.close();

        // Print out the Employees
        stmt = con.createStatement();
        rs = stmt.executeQuery("SELECT * FROM EMP");
        // Loop through and print the employee number, job, and hiredate
        while (rs.next()) {
            int id = rs.getInt("EMPNO");
            int job = rs.getInt("JOB");
            String hireDate = rs.getString("HIREDATE");

            System.out.println(id + ":" + job + ":" + hireDate);
        }
        con.close();
    } catch (SQLException ex) {
        ex.printStackTrace();
    }
}

From source file:friendsandfollowers.DBFollowersIDs.java

public static void main(String[] args) throws ClassNotFoundException, SQLException, JSONException,
        FileNotFoundException, UnsupportedEncodingException {

    // Check arguments that passed in
    if ((args == null) || (args.length == 0)) {
        System.err.println("2 Parameters are required plus one optional " + "parameter to launch a Job.");
        System.err.println("First: String 'OUTPUT: /output/path/'");
        System.err.println("Second: (int) Number of ids to fetch. " + "Provide number which increment by 5000 "
                + "(5000, 10000, 15000 etc) " + "or -1 to fetch all ids.");
        System.err.println("Third (optional): 'screen_name / user_id_str'");
        System.err.println("If 3rd argument not provided then provide" + " Twitter users through database.");
        System.exit(-1);/*from  w  w w  .  j  av a  2 s . c  om*/
    }

    MysqlDB DB = new MysqlDB();
    AppOAuth AppOAuths = new AppOAuth();
    Misc helpers = new Misc();
    String endpoint = "/followers/ids";

    String OutputDirPath = null;
    try {
        OutputDirPath = StringEscapeUtils.escapeJava(args[0]);
    } catch (Exception e) {
        System.err.println("Argument" + args[0] + " must be an String.");
        System.exit(-1);
    }

    int IDS_TO_FETCH_INT = -1;
    try {
        IDS_TO_FETCH_INT = Integer.parseInt(args[1]);
    } catch (NumberFormatException e) {
        System.err.println("Argument" + args[1] + " must be an integer.");
        System.exit(-1);
    }

    int IDS_TO_FETCH = 0;
    if (IDS_TO_FETCH_INT > 5000) {

        float IDS_TO_FETCH_F = (float) IDS_TO_FETCH_INT / 5000;
        IDS_TO_FETCH = (int) Math.ceil(IDS_TO_FETCH_F);
    } else if ((IDS_TO_FETCH_INT <= 5000) && (IDS_TO_FETCH_INT > 0)) {
        IDS_TO_FETCH = 1;
    }

    String targetedUser = "";
    if (args.length == 3) {
        try {
            targetedUser = StringEscapeUtils.escapeJava(args[2]);
        } catch (Exception e) {
            System.err.println("Argument" + args[2] + " must be an String.");
            System.exit(-1);
        }
    }

    try {

        TwitterFactory tf = AppOAuths.loadOAuthUser(endpoint);
        Twitter twitter = tf.getInstance();

        int RemainingCalls = AppOAuths.RemainingCalls;
        int RemainingCallsCounter = 0;
        System.out.println("First Time Remianing Calls: " + RemainingCalls);

        String Screen_name = AppOAuths.screen_name;
        System.out.println("First Time Loaded OAuth Screen_name: " + Screen_name);

        IDs ids;
        System.out.println("Listing followers ids.");

        // if targetedUser not provided by argument, then look into database.
        if (StringUtils.isEmpty(targetedUser)) {

            String selectQuery = "SELECT * FROM `followers_parent` WHERE " + "`targeteduser` != '' AND "
                    + "`nextcursor` != '0' AND " + "`nextcursor` != '2'";

            ResultSet results = DB.selectQ(selectQuery);

            int numRows = DB.numRows(results);
            if (numRows < 1) {
                System.err.println("No User in database to get followersIDS");
                System.exit(-1);
            }

            OUTERMOST: while (results.next()) {

                int followers_parent_id = results.getInt("id");
                targetedUser = results.getString("targeteduser");
                long cursor = results.getLong("nextcursor");
                System.out.println("Targeted User: " + targetedUser);

                int idsLoopCounter = 0;
                int totalIDs = 0;

                // put idsJSON in a file
                PrintWriter writer = new PrintWriter(OutputDirPath + "/" + targetedUser, "UTF-8");

                // call different functions for screen_name and id_str
                Boolean chckedNumaric = helpers.isNumeric(targetedUser);

                do {
                    ids = null;
                    try {

                        if (chckedNumaric) {

                            long LongValueTargetedUser = Long.valueOf(targetedUser).longValue();

                            ids = twitter.getFollowersIDs(LongValueTargetedUser, cursor);
                        } else {
                            ids = twitter.getFollowersIDs(targetedUser, cursor);
                        }

                    } catch (TwitterException te) {

                        // do not throw if user has protected tweets, 
                        // or if they deleted their account
                        if (te.getStatusCode() == HttpResponseCode.UNAUTHORIZED
                                || te.getStatusCode() == HttpResponseCode.NOT_FOUND) {

                            System.out.println(targetedUser + " is protected or account is deleted");
                        } else {
                            System.out.println("Followers Get Exception: " + te.getMessage());
                        }

                        // If rate limit reached then switch Auth user
                        RemainingCallsCounter++;
                        if (RemainingCallsCounter >= RemainingCalls) {

                            // load auth user
                            tf = AppOAuths.loadOAuthUser(endpoint);
                            twitter = tf.getInstance();

                            System.out.println(
                                    "New User Loaded OAuth" + " Screen_name: " + AppOAuths.screen_name);

                            RemainingCalls = AppOAuths.RemainingCalls;
                            RemainingCallsCounter = 0;

                            System.out.println("New Remianing Calls: " + RemainingCalls);
                        }

                        // update cursor in "followers_parent"
                        String fieldValues = "`nextcursor` = 2";
                        String where = "id = " + followers_parent_id;
                        DB.Update("`followers_parent`", fieldValues, where);

                        // If error then switch to next user
                        continue OUTERMOST;
                    }

                    if (ids.getIDs().length > 0) {

                        idsLoopCounter++;
                        totalIDs += ids.getIDs().length;
                        System.out.println(idsLoopCounter + ": IDS length: " + ids.getIDs().length);

                        JSONObject responseDetailsJson = new JSONObject();
                        JSONArray jsonArray = new JSONArray();
                        for (long id : ids.getIDs()) {
                            jsonArray.put(id);
                        }
                        Object idsJSON = responseDetailsJson.put("ids", jsonArray);

                        writer.println(idsJSON);
                    }

                    // If rate limit reached then switch Auth user
                    RemainingCallsCounter++;
                    if (RemainingCallsCounter >= RemainingCalls) {

                        // load auth user
                        tf = AppOAuths.loadOAuthUser(endpoint);
                        twitter = tf.getInstance();

                        System.out.println("New User Loaded OAuth " + "Screen_name: " + AppOAuths.screen_name);

                        RemainingCalls = AppOAuths.RemainingCalls;
                        RemainingCallsCounter = 0;

                        System.out.println("New Remianing Calls: " + RemainingCalls);
                    }

                    if (IDS_TO_FETCH_INT != -1) {
                        if (idsLoopCounter == IDS_TO_FETCH) {
                            break;
                        }
                    }

                } while ((cursor = ids.getNextCursor()) != 0);
                writer.close();
                System.out.println("Total ids dumped of " + targetedUser + " are: " + totalIDs);
                System.out.println();

                // update cursor in "followers_parent"
                String fieldValues = "`nextcursor` = " + cursor;
                String where = "id = " + followers_parent_id;
                DB.Update("`followers_parent`", fieldValues, where);

            } // loop through every result found in db
        } else {

            // Second Argument Set, so we are here.
            System.out.println("screen_name / user_id_str passed by argument");

            int idsLoopCounter = 0;
            int totalIDs = 0;

            // put idsJSON in a file
            PrintWriter writer = new PrintWriter(
                    OutputDirPath + "/" + targetedUser + "_ids_" + helpers.getUnixTimeStamp(), "UTF-8");

            // call different functions for screen_name and id_str
            Boolean chckedNumaric = helpers.isNumeric(targetedUser);
            long cursor = -1;

            do {
                ids = null;
                try {

                    if (chckedNumaric) {

                        long LongValueTargetedUser = Long.valueOf(targetedUser).longValue();

                        ids = twitter.getFollowersIDs(LongValueTargetedUser, cursor);
                    } else {
                        ids = twitter.getFollowersIDs(targetedUser, cursor);
                    }

                } catch (TwitterException te) {

                    // do not throw if user has protected tweets, or if they deleted their account
                    if (te.getStatusCode() == HttpResponseCode.UNAUTHORIZED
                            || te.getStatusCode() == HttpResponseCode.NOT_FOUND) {

                        System.out.println(targetedUser + " is protected or account is deleted");
                    } else {
                        System.out.println("Followers Get Exception: " + te.getMessage());
                    }
                    System.exit(-1);
                }

                if (ids.getIDs().length > 0) {

                    idsLoopCounter++;
                    totalIDs += ids.getIDs().length;
                    System.out.println(idsLoopCounter + ": IDS length: " + ids.getIDs().length);

                    JSONObject responseDetailsJson = new JSONObject();
                    JSONArray jsonArray = new JSONArray();

                    for (long id : ids.getIDs()) {
                        jsonArray.put(id);
                    }

                    Object idsJSON = responseDetailsJson.put("ids", jsonArray);
                    writer.println(idsJSON);
                }

                // If rate limit reach then switch Auth user
                RemainingCallsCounter++;
                if (RemainingCallsCounter >= RemainingCalls) {

                    // load auth user
                    tf = AppOAuths.loadOAuthUser(endpoint);
                    twitter = tf.getInstance();

                    System.out.println("New User Loaded OAuth Screen_name: " + AppOAuths.screen_name);

                    RemainingCalls = AppOAuths.RemainingCalls;
                    RemainingCallsCounter = 0;

                    System.out.println("New Remianing Calls: " + RemainingCalls);
                }

                if (IDS_TO_FETCH_INT != -1) {
                    if (idsLoopCounter == IDS_TO_FETCH) {
                        break;
                    }
                }

            } while ((cursor = ids.getNextCursor()) != 0);
            writer.close();

            System.out.println("Total ids dumped of " + targetedUser + " are: " + totalIDs);
            System.out.println();
        }

    } catch (TwitterException te) {
        // te.printStackTrace();
        System.err.println("Failed to get followers' ids: " + te.getMessage());
        System.exit(-1);
    }
    System.out.println("!!!! DONE !!!!");
}

From source file:friendsandfollowers.DBFriendsIDs.java

public static void main(String[] args) throws ClassNotFoundException, SQLException, JSONException,
        FileNotFoundException, UnsupportedEncodingException {

    // Check arguments that passed in
    if ((args == null) || (args.length == 0)) {
        System.err.println("2 Parameters are required plus one optional " + "parameter to launch a Job.");
        System.err.println("First: String 'OUTPUT: /output/path/'");
        System.err.println("Second: (int) Number of ids to fetch. " + "Provide number which increment by 5000 "
                + "(5000, 10000, 15000 etc) " + "or -1 to fetch all ids.");
        System.err.println("Third (optional): 'screen_name / user_id_str'");
        System.err.println("If 3rd argument not provided then provide" + " Twitter users through database.");
        System.exit(-1);//  w  ww  . j  av a  2s  . c o  m
    }

    MysqlDB DB = new MysqlDB();
    AppOAuth AppOAuths = new AppOAuth();
    Misc helpers = new Misc();
    String endpoint = "/friends/ids";

    String OutputDirPath = null;
    try {
        OutputDirPath = StringEscapeUtils.escapeJava(args[0]);
    } catch (Exception e) {
        System.err.println("Argument" + args[0] + " must be an String.");
        System.exit(-1);
    }

    int IDS_TO_FETCH_INT = -1;
    try {
        IDS_TO_FETCH_INT = Integer.parseInt(args[1]);
    } catch (NumberFormatException e) {
        System.err.println("Argument" + args[1] + " must be an integer.");
        System.exit(-1);
    }

    int IDS_TO_FETCH = 0;
    if (IDS_TO_FETCH_INT > 5000) {

        float IDS_TO_FETCH_F = (float) IDS_TO_FETCH_INT / 5000;
        IDS_TO_FETCH = (int) Math.ceil(IDS_TO_FETCH_F);
    } else if ((IDS_TO_FETCH_INT <= 5000) && (IDS_TO_FETCH_INT > 0)) {
        IDS_TO_FETCH = 1;
    }

    String targetedUser = "";
    if (args.length == 3) {
        try {
            targetedUser = StringEscapeUtils.escapeJava(args[2]);
        } catch (Exception e) {
            System.err.println("Argument" + args[2] + " must be an String.");
            System.exit(-1);
        }
    }

    try {

        TwitterFactory tf = AppOAuths.loadOAuthUser(endpoint);
        Twitter twitter = tf.getInstance();

        int RemainingCalls = AppOAuths.RemainingCalls;
        int RemainingCallsCounter = 0;
        System.out.println("First Time Remianing Calls: " + RemainingCalls);

        String Screen_name = AppOAuths.screen_name;
        System.out.println("First Time Loaded OAuth Screen_name: " + Screen_name);

        IDs ids;
        System.out.println("Listing friends ids.");

        // if targetedUser not provided by argument, then look into database.
        if (StringUtils.isEmpty(targetedUser)) {

            String selectQuery = "SELECT * FROM `followings_parent` WHERE " + "`targeteduser` != '' AND "
                    + "`nextcursor` != '0' AND " + "`nextcursor` != '2'";

            ResultSet results = DB.selectQ(selectQuery);

            int numRows = DB.numRows(results);
            if (numRows < 1) {
                System.err.println("No User in database to get friendsIDS");
                System.exit(-1);
            }

            OUTERMOST: while (results.next()) {

                int following_parent_id = results.getInt("id");
                targetedUser = results.getString("targeteduser");
                long cursor = results.getLong("nextcursor");
                System.out.println("Targeted User: " + targetedUser);

                int idsLoopCounter = 0;
                int totalIDs = 0;

                // put idsJSON in a file
                PrintWriter writer = new PrintWriter(OutputDirPath + "/" + targetedUser, "UTF-8");

                // call different functions for screen_name and id_str
                Boolean chckedNumaric = helpers.isNumeric(targetedUser);

                do {
                    ids = null;
                    try {

                        if (chckedNumaric) {

                            long LongValueTargetedUser = Long.valueOf(targetedUser).longValue();

                            ids = twitter.getFriendsIDs(LongValueTargetedUser, cursor);
                        } else {
                            ids = twitter.getFriendsIDs(targetedUser, cursor);
                        }

                    } catch (TwitterException te) {

                        // do not throw if user has protected tweets, 
                        // or if they deleted their account
                        if (te.getStatusCode() == HttpResponseCode.UNAUTHORIZED
                                || te.getStatusCode() == HttpResponseCode.NOT_FOUND) {

                            System.out.println(targetedUser + " is protected or account is deleted");
                        } else {
                            System.out.println("Friends Get Exception: " + te.getMessage());
                        }

                        // If rate limit reached then switch Auth user
                        RemainingCallsCounter++;
                        if (RemainingCallsCounter >= RemainingCalls) {

                            // load auth user
                            tf = AppOAuths.loadOAuthUser(endpoint);
                            twitter = tf.getInstance();

                            System.out.println(
                                    "New User Loaded OAuth" + " Screen_name: " + AppOAuths.screen_name);

                            RemainingCalls = AppOAuths.RemainingCalls;
                            RemainingCallsCounter = 0;

                            System.out.println("New Remianing Calls: " + RemainingCalls);
                        }

                        // update cursor in "followings_parent"
                        String fieldValues = "`nextcursor` = 2";
                        String where = "id = " + following_parent_id;
                        DB.Update("`followings_parent`", fieldValues, where);

                        // If error then switch to next user
                        continue OUTERMOST;
                    }

                    if (ids.getIDs().length > 0) {

                        idsLoopCounter++;
                        totalIDs += ids.getIDs().length;
                        System.out.println(idsLoopCounter + ": IDS length: " + ids.getIDs().length);

                        JSONObject responseDetailsJson = new JSONObject();
                        JSONArray jsonArray = new JSONArray();
                        for (long id : ids.getIDs()) {
                            jsonArray.put(id);
                        }
                        Object idsJSON = responseDetailsJson.put("ids", jsonArray);

                        writer.println(idsJSON);
                    }

                    // If rate limit reached then switch Auth user.
                    RemainingCallsCounter++;
                    if (RemainingCallsCounter >= RemainingCalls) {

                        // load auth user
                        tf = AppOAuths.loadOAuthUser(endpoint);
                        twitter = tf.getInstance();

                        System.out.println("New User Loaded OAuth " + "Screen_name: " + AppOAuths.screen_name);

                        RemainingCalls = AppOAuths.RemainingCalls;
                        RemainingCallsCounter = 0;

                        System.out.println("New Remianing Calls: " + RemainingCalls);
                    }

                    if (IDS_TO_FETCH_INT != -1) {
                        if (idsLoopCounter == IDS_TO_FETCH) {
                            break;
                        }
                    }

                } while ((cursor = ids.getNextCursor()) != 0);
                writer.close();
                System.out.println("Total ids dumped of " + targetedUser + " are: " + totalIDs);
                System.out.println();

                // update cursor in "followings_parent"
                String fieldValues = "`nextcursor` = " + cursor;
                String where = "id = " + following_parent_id;
                DB.Update("`followings_parent`", fieldValues, where);

            } // loop through every result found in db
        } else {

            // Second Argument Sets, so we are here.
            System.out.println("screen_name / user_id_str " + "passed by argument");

            int idsLoopCounter = 0;
            int totalIDs = 0;

            // put idsJSON in a file
            PrintWriter writer = new PrintWriter(
                    OutputDirPath + "/" + targetedUser + "_ids_" + helpers.getUnixTimeStamp(), "UTF-8");

            // call different functions for screen_name and id_str
            Boolean chckedNumaric = helpers.isNumeric(targetedUser);
            long cursor = -1;

            do {
                ids = null;
                try {

                    if (chckedNumaric) {

                        long LongValueTargetedUser = Long.valueOf(targetedUser).longValue();

                        ids = twitter.getFriendsIDs(LongValueTargetedUser, cursor);
                    } else {
                        ids = twitter.getFriendsIDs(targetedUser, cursor);
                    }

                } catch (TwitterException te) {

                    // do not throw if user has protected tweets, 
                    // or if they deleted their account
                    if (te.getStatusCode() == HttpResponseCode.UNAUTHORIZED
                            || te.getStatusCode() == HttpResponseCode.NOT_FOUND) {

                        System.out.println(targetedUser + " is protected or account is deleted");
                    } else {
                        System.out.println("Friends Get Exception: " + te.getMessage());
                    }
                    System.exit(-1);
                }

                if (ids.getIDs().length > 0) {

                    idsLoopCounter++;
                    totalIDs += ids.getIDs().length;
                    System.out.println(idsLoopCounter + ": IDS length: " + ids.getIDs().length);

                    JSONObject responseDetailsJson = new JSONObject();
                    JSONArray jsonArray = new JSONArray();
                    for (long id : ids.getIDs()) {
                        jsonArray.put(id);
                    }
                    Object idsJSON = responseDetailsJson.put("ids", jsonArray);

                    writer.println(idsJSON);

                }

                // If rate limit reach then switch Auth user
                RemainingCallsCounter++;
                if (RemainingCallsCounter >= RemainingCalls) {

                    // load auth user
                    tf = AppOAuths.loadOAuthUser(endpoint);
                    twitter = tf.getInstance();

                    System.out.println("New User Loaded OAuth Screen_name: " + AppOAuths.screen_name);

                    RemainingCalls = AppOAuths.RemainingCalls;
                    RemainingCallsCounter = 0;

                    System.out.println("New Remianing Calls: " + RemainingCalls);
                }

                if (IDS_TO_FETCH_INT != -1) {
                    if (idsLoopCounter == IDS_TO_FETCH) {
                        break;
                    }
                }

            } while ((cursor = ids.getNextCursor()) != 0);
            writer.close();
            System.out.println("Total ids dumped of " + targetedUser + " are: " + totalIDs);
            System.out.println();

        }

    } catch (TwitterException te) {
        // te.printStackTrace();
        System.err.println("Failed to get friends' ids: " + te.getMessage());
        System.exit(-1);
    }
    System.out.println("!!!! DONE !!!!");
}

From source file:InsertRowBug.java

public static void main(String args[]) {

    String url;//from w  ww .  j  a  v a2  s.c o  m
    // url = "jdbc:odbc:SQL Anywhere 5.0 Sample";
    // url = "jdbc:oracle:thin:@server:1521:db570";
    url = "jdbc:odbc:RainForestDSN";

    String driver;
    //driver = "oracle.jdbc.driver.OracleDriver";
    driver = "sun.jdbc.odbc.JdbcOdbcDriver";

    String user, pass;
    user = "student";
    pass = "student";

    Connection con;
    Statement stmt;
    ResultSet uprs;

    try {
        Class.forName(driver);

    } catch (java.lang.ClassNotFoundException e) {
        System.err.println(e);
        return;
    }

    try {
        con = DriverManager.getConnection(url, user, pass);
        stmt = con.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_UPDATABLE);
        uprs = stmt.executeQuery("SELECT * FROM Music_Recordings");

        // Check the column count
        ResultSetMetaData md = uprs.getMetaData();
        System.out.println("Resultset has " + md.getColumnCount() + " cols.");

        int rowNum = uprs.getRow();
        System.out.println("row1 " + rowNum);
        uprs.absolute(1);
        rowNum = uprs.getRow();
        System.out.println("row2 " + rowNum);
        uprs.next();
        uprs.moveToInsertRow();
        uprs.updateInt(1, 150);
        uprs.updateString(2, "Madonna");
        uprs.updateString(3, "Dummy");
        uprs.updateString(4, "Jazz");
        uprs.updateString(5, "Image");
        uprs.updateInt(6, 5);
        uprs.updateDouble(7, 5);
        uprs.updateInt(8, 15);
        uprs.insertRow();
        uprs.close();
        stmt.close();
        con.close();
    } catch (SQLException ex) {
        System.err.println("SQLException: " + ex.getMessage());
    }
}

From source file:edu.caltechUcla.sselCassel.projects.jMarkets.server.data.DBConnector.java

/** Initialize the database */
public static void main(String args[]) {
    Connection conn = null;/*from  w  w  w  .j a v a 2s  .com*/
    ResultSet rs = null;
    try {
        DBConnector dbc = new DBConnector(null);
        dbc.dbURL = "jdbc:mysql://localhost:3306/jmarkets2?autoReconnect=true";
        //dbc.dbPort = "3306";
        dbc.dbUser = "root";
        dbc.dbPassword = "";
        //dbc.dbName = "jmarkets";

        conn = dbc.getConnection();
        String query = "select * from jm_user";
        Object[] results = dbc.executeQuery(query, conn);
        rs = (ResultSet) results[0];
        System.out.println("" + rs.next());

        System.out.println(rs.getString("email"));

    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        try {
            rs.close();
        } catch (Exception e) {
        }
        try {
            conn.close();
        } catch (Exception e) {
        }
    }
}

From source file:RSMetaDataMethods.java

public static void main(String args[]) {

    String url = "jdbc:mySubprotocol:myDataSource";
    Connection con;//  www .ja  v  a2 s .  c o m
    Statement stmt;

    try {
        Class.forName("myDriver.ClassName");

    } catch (java.lang.ClassNotFoundException e) {
        System.err.print("ClassNotFoundException: ");
        System.err.println(e.getMessage());
    }

    try {
        con = DriverManager.getConnection(url, "myLogin", "myPassword");

        stmt = con.createStatement();

        ResultSet rs = stmt.executeQuery("select * from COFFEES");
        ResultSetMetaData rsmd = rs.getMetaData();

        int numberOfColumns = rsmd.getColumnCount();
        for (int i = 1; i <= numberOfColumns; i++) {
            String colName = rsmd.getColumnName(i);
            String tableName = rsmd.getTableName(i);
            String name = rsmd.getColumnTypeName(i);
            boolean caseSen = rsmd.isCaseSensitive(i);
            boolean writable = rsmd.isWritable(i);
            System.out.println("Information for column " + colName);
            System.out.println("    Column is in table " + tableName);
            System.out.println("    DBMS name for type is " + name);
            System.out.println("    Is case sensitive:  " + caseSen);
            System.out.println("    Is possibly writable:  " + writable);
            System.out.println("");
        }

        while (rs.next()) {
            for (int i = 1; i <= numberOfColumns; i++) {
                String s = rs.getString(i);
                System.out.print(s + "  ");
            }
            System.out.println("");
        }

        stmt.close();
        con.close();

    } catch (SQLException ex) {
        System.err.println("SQLException: " + ex.getMessage());
    }
}

From source file:HSqlPrimerDesign.java

public static void main(String[] args) throws NoSuchFieldException, IllegalAccessException,
        ClassNotFoundException, InstantiationException, SQLException, FileNotFoundException {
    Class.forName(JDBC_DRIVER_HSQL).newInstance();
    conn = DriverManager.getConnection(DB_SERVER_URL, USER, PASS);
    PrintWriter log = new PrintWriter(new File("javalog.log"));
    DpalLoad.main(args);//  w w  w . jav  a2 s.  c  o  m
    Dpal_Inst = DpalLoad.INSTANCE_WIN64;
    //        int[][] arr =calcHairpin("GGGGGGCCCCCCCCCCCCGGGGGGG",4);
    //        if(arr.length<=1){
    //            System.out.println("No Hairpin's found");
    //        }else{
    //            System.out.println("Hairpin(s) found");
    //        }
    Statement stat = conn.createStatement();
    ResultSet call = stat.executeQuery(
            "Select * From " + "Primerdb.primers where Cluster ='A1' and UniqueP =True and Bp = 20");
    Set<CharSequence> primers = new HashSet<>();
    while (call.next()) {
        primers.add(call.getString("Sequence"));
    }
    //        primers.stream().forEach(x->{
    //            log.println(x);
    //            log.println(complementarity(x, x, Dpal_Inst));
    //            int[][] arr =calcHairpin((String)x,4);
    //            if(arr.length<=1){
    //                log.println("No Hairpin's found");
    //            }else{
    //                log.println("Hairpin(s) found");
    //            }
    //            log.println();
    //            log.flush();
    //        });
}

From source file:SimpleProgramToAccessOracleDatabase.java

public static void main(String[] args) throws SQLException {
    Connection conn = null; // connection object
    Statement stmt = null; // statement object
    ResultSet rs = null; // result set object
    try {/*from w  w  w .  j a v a  2  s  . c  om*/
        conn = getConnection(); // without Connection, can not do much
        // create a statement: This object will be used for executing
        // a static SQL statement and returning the results it produces.
        stmt = conn.createStatement();
        // start a transaction
        conn.setAutoCommit(false);

        // create a table called cats_tricks
        stmt.executeUpdate("CREATE TABLE cats_tricks " + "(name VARCHAR2(30), trick VARCHAR2(30))");
        // insert two new records to the cats_tricks table
        stmt.executeUpdate("INSERT INTO cats_tricks VALUES('mono', 'r')");
        stmt.executeUpdate("INSERT INTO cats_tricks VALUES('mono', 'j')");

        // commit the transaction
        conn.commit();

        // set auto commit to true (from now on every single
        // statement will be treated as a single transaction
        conn.setAutoCommit(true);

        // get all of the the records from the cats_tricks table
        rs = stmt.executeQuery("SELECT name, trick FROM cats_tricks");

        // iterate the result set and get one row at a time
        while (rs.next()) {
            String name = rs.getString(1); // 1st column in query
            String trick = rs.getString(2); // 2nd column in query
            System.out.println("name=" + name);
            System.out.println("trick=" + trick);
            System.out.println("==========");
        }
    } catch (ClassNotFoundException ce) {
        // if the driver class not found, then we will be here
        System.out.println(ce.getMessage());
    } catch (SQLException e) {
        // something went wrong, we are handling the exception here
        if (conn != null) {
            conn.rollback();
            conn.setAutoCommit(true);
        }

        System.out.println("--- SQLException caught ---");
        // iterate and get all of the errors as much as possible.
        while (e != null) {
            System.out.println("Message   : " + e.getMessage());
            System.out.println("SQLState  : " + e.getSQLState());
            System.out.println("ErrorCode : " + e.getErrorCode());
            System.out.println("---");
            e = e.getNextException();
        }
    } finally { // close db resources
        try {
            rs.close();
            stmt.close();
            conn.close();
        } catch (Exception e) {
        }

    }
}