I have got a table of blacklisted Bluetooth devices and need to make sure that my device is paired with none of them. The blacklisted devices are stored in a database accessed through a content provider.

Which of the approaches is better?

  • I build an IN clause and then query data once. The IN clause might contain very many values. For example.

SELECT _id FROM blacklisted_devices WHERE mac_address IN ('01:23:45:67:89:ab', ' ab:23:45:67:89:df') OR device_name IN ('Lorem', 'Ipsum')

  • I use a for loop and query data in it.

    Set<BluetoothDevice> bondedDevices = BluetoothAdapter.getDefaultAdapter().getBondedDevices();
    Cursor cursor = null;
    for (BluetoothDevice device : bondedDevices) {
        cursor = getContentResolver().query(Uris.BLUETOOTH,
                new String[] { Columns._ID },
                Columns.DEVICE_NAME + "=? OR " + Columns.MAC_ADDRESS + "=?",
                new String[] { device.getName(), device.getAddress() },
                null);
        if (cursor.getCount() > 0) {
            // Unpair
        }
    }
    
有帮助吗?

解决方案

If the list of values to check is stored in the same database as the blacklist table, then the fastest and easiest way would be to compare them directly:

SELECT _id
FROM blacklisted_devices
WHERE mac_address IN (SELECT mac_address FROM my_list)
      ...

However, this is not the case here; if you had access to the database, you wouldn't need a content resolver.

Comparing multiple values with an IN clause is much faster. This should be preferred as long as you do not exceed one of the database limits.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top