public long fillTables() {
    // list of relevant source-tables
    Iterator it = tables.listIterator();
    // holds results of each queried source table
    ResultSet result;
    // buffer to build SQL-statement for inserting remote data into local temp. table
    // (StringBuffer is much faster than String)
    StringBuffer statement=new StringBuffer("");
    // name of current source table
    String srctable="";
    // number of columns in database table
    int columnCount;
    long rowcount = 0;

    // add the database identifier into the SELECT statement
    queryStr = queryStr.replaceAll("databaseID", ""+databaseID);
    
    // iterate through all relevant source-tables
    while (it.hasNext()) {
      try {

        // check if source and dest. database are the same
        if (dbIdentical) {

            // databases identical, read data directly via SQL into temporary table
            srctable = (String)it.next();
            rowcount += destDB.executeUpdate("INSERT IGNORE INTO "+tmpTable+" "+queryStr.replaceAll("#srctable#",srctable));

        } else {
            // databases not identical, transfer data "manually"
	    //
	    final int MAX_ROWS = 50000;
            // read data from source-table
            srctable = (String)it.next();
	    String curQueryStr = queryStr.replaceAll("#srctable#",srctable);
	    long pos = 0;
	    boolean firstValue;
	    statement = new StringBuffer();
	    do {
		// read only 50000 rows in one step to avoid heap space out of memory error
		result = sourceDB.executeQuery(curQueryStr+" LIMIT "+pos+","+MAX_ROWS);
		columnCount = result.getMetaData().getColumnCount();
		statement.append("INSERT IGNORE INTO "+tmpTable+" VALUES ");

		// insert data into local temporary table
		// compose SQL-INSERT statement from extracted remote data
		firstValue=true;
		while (result.next()) {
		    if (!firstValue) {
			statement.append(",");
		    } else firstValue=false;
		    statement.append("(");
		    int i;
		    for (i=1; i<columnCount; i++) {
			statement.append("'"+result.getString(i)+"',");
		    }
		    statement.append("'"+result.getString(i)+"')");
		}
		// execute INSERT-statement (but only if it contains any data)
		if (!firstValue)
		    rowcount +=  destDB.executeUpdate(statement.toString());
		// release results and statement buffer
		result.close();
		statement.setLength(0);
		pos += MAX_ROWS;
	    } while(!firstValue);
        }

      } catch (SQLException e) {
            // error, report to caller
            output += "Error while filling temporary database from source table "+srctable+"!";
            output += "<p>"+e.getMessage()+"<p>";        
            success = false;
	    return 0;
      }
      
    } // while (it.hasNext())
    return rowcount;
  }