Home > Mobile >  How can I pass integer into string for sql query
How can I pass integer into string for sql query

Time:11-30

I have written a program that extracts data from an SQL table:

String url = "jdbc:mysql://localhost/petcare";
        String password = "ParkSideRoad161997";
        String username = "root";
        // Step 2: Making connection using
        // Connection type and inbuilt function on
//        Connection con = null;
        PreparedStatement p = null;
        ResultSet rs = null;
 
        // Try block to catch exception/s
        try {
            Connection con = DriverManager.getConnection(url, username, password);
            // SQL command data stored in String datatype
            String sql = "select * from inbox";
            p = con.prepareStatement(sql);
            rs = p.executeQuery();
 
            // Printing ID, name, email of customers
            // of the SQL command above
            System.out.println("inboxId");
            int inboxId;
 
            // Condition check
            while (rs.next()) {
 
                  inboxId = rs.getInt("InboxId");
//                System.out.println(inboxId);
            }
            
            String sql2 = "select * from message where inboxId = int";//this is where i need help
            p = con.prepareStatement(sql2);
            rs = p.executeQuery();
         
            // Printing ID, name, email of customers
            // of the SQL command above
            System.out.println("Inbox:");
            
        }
 
        // Catch block to handle exception
        catch (SQLException e) {
 
            // Print exception pop-up on screen
            System.out.println(e);
        }

Once I get the inboxId, I want to run sql2 and pass inboxId as int. How can I do this. Each user will have a different inboxId so thats why to get the user inbox I want to extract and messages in the message table that are meant for inboxId of the user.

I tried the query string sql and it works now I just need to fix String sql2.

CodePudding user response:

String sql2 = "select * from message where inboxId = " 1234;

1234 could be a variable. You could also use String.format() to do it as well.

String sql2 = String.format("select * from message where inboxId = %d", 1234);

CodePudding user response:

Try this:

  String sql2 = "select * from message where inboxId = ?"; //The ? indicates a variable in the prepared statement.
  p = con.prepareStatement(sql2);
  p.setInt(1, inboxId);
  rs = p.executeQuery();
  • Related