dev
dev

Reputation: 181

JAVA - MySQL an ArrayList

I have query from MySQl

String sqlSearch = "SELECT * from Item"

and method with ArrayList

  public static ArrayList<String> checkNo() throws SQLException {

    ArrayList<String> no= new ArrayList<String>();

    DbManager db = new DbManager();
    db.connect();
    String sql = "SELECT * from Category where id = " + idUser + " ";

    Statement stmt = db.connect().createStatement();
    ResultSet rs = stmt.executeQuery(sql);

    while (rs.next()) {

        no.add(rs.getString("nameCategory"));

    }
    db.disconnect();
    return no;
}

And I get from specific user his category in arraylist, but how to pass this category to sqlSearch???

  SELECT * from Item where category ????
  data from ArrayList

Any idea?

Upvotes: 0

Views: 641

Answers (4)

nafas
nafas

Reputation: 5433

There are many ways of doing this,

one way is two combine two queries:

SELECT * from Item where category in (SELECT nameCategory from Category where id = idUser )

as suggested its better to use prepared statement.

Upvotes: 0

Hema
Hema

Reputation: 986

As your query is not clear am giving you a sample code,jus try it

if (count > 0) {
        for (int i = 0; i < count; i++) {
            ColumnName= no.get(i).getColumnName();
            }
        getItemQuery = "FROM Item where category in (" +ColumnName + ")";
    }

Upvotes: 0

Mehmood Memon
Mehmood Memon

Reputation: 1149

Your checkNo() method return an ArrayList. It looks like this ArrayList will have only one item, get that item from the ArrayList and pass it to the query like this.

String category = list.get(i);    
"Select * from Item where category = "+category;

Upvotes: 0

Stefano Zanini
Stefano Zanini

Reputation: 5926

You could loop through the ArrayList items and build a String to use in the where clause like this

String inCondition = "";
boolean first = true;
ArrayList<String> categories = checkNo();

for(String cat : categories){
    if(first){
        first = false;
    } else {
        inCondition += ",";
    }
    inCondition += cat;
}

String sqlSearch = "SELECT * from Item where category in (" + inCondition + ")";

Upvotes: 1

Related Questions