0

I am searching for short version for this kind of code:

        if (database_1[0].equalsIgnoreCase(data)) {

            preparedStatement = connect
                    .prepareStatement("update SLIP.CONTACTS set`database_1`=? where user='"
                            + user + "'");

            preparedStatement.setString(1, vnos );
            preparedStatement.executeUpdate();

        }       else if (database_2[0].equalsIgnoreCase(data)) {

            preparedStatement = connect
                    .prepareStatement("update SLIP.CONTACTS set`database_2`=? where user='"
                            + user + "'");

            preparedStatement.setString(1, vnos );
            preparedStatement.executeUpdate();

        }

So database_1[0] is a String array. And I need his first element to check if equals a string data. Is there a shortcut (for loop) to change database_1[0] to database_2[0] and then to database_3[0] and so on..thx in advance for help

4

2 回答 2

1

Multi-dimensional array?

for (int j = 0; j < numberOfDatabases; j++) {
    if (database[j][0].equalsIgnoreCase(data)) {
        preparedStatement = connect
                           .prepareStatement("update SLIP.CONTACTS set `database_" 
                                                 + j + "`=? where user=?");

        preparedStatement.setString(1, vnos);
        preparedStatement.setString(2, user);
        preparedStatement.executeUpdate();

        break;
    }
}

Or better yet, use an appropriate data structure to hold your database references.

List<String[]> databases = new ArrayList<String[]>();

// Populate databases.

for (int j = 0; j < databases.size(); j++) {
    if (database.get(j)[0].equalsIgnoreCase(data)) {
        preparedStatement = connect
                           .prepareStatement("update SLIP.CONTACTS set `database_" 
                                                 + j + "`=? where user=?");

        preparedStatement.setString(1, vnos);
        preparedStatement.setString(2, user);
        preparedStatement.executeUpdate();

        break;
    }
}

Notice that here I index from 0 to size - 1.

To javaL's point, you can also replace user in your PreparedStatement as noted above.

于 2013-10-17T17:00:06.220 回答
0

You could use a nested array.

String [][] databases = new String[numberOfDatabases][itemsInEachDatabase];

for (int i = 0; i < itemsInEachDatabase; i++) {
  databases[0][i] = database_1[i];
}
// repeat this for loop for other databases

for (int i = 0; i < numberOfDatabases; i++) {
  if (databases[i][0].equalsIgnoreCase(data)) {
    // your code here
  }
}
于 2013-10-17T17:05:00.470 回答