34

Can someone answer on my dilemma which method to use for connecting Android device to mySQL or Postgresql?

I can do it in both ways without any errors and problems, with no noticeable difference but everyone recommend web service instead of using jdbc driver and direct connection,

Can someone explain why with some facts?

EDIT: I did'n mention that is more simple and needs less time to do it over jdbc. So, why web service, or why not?

2
  • 3
    1. if you use a web service, it will work with other clients (like ipad). 2. look at Spring Data Rest, which should help you make a restful web service quite quickly Apr 6, 2013 at 18:05
  • what thing u changed for connecting android REAL device to postgreSQL, becuase in my case it works only when it run on emulator and for real device it shows connection attempt failed Nov 15, 2022 at 17:04

5 Answers 5

38

You think it's simpler and faster to do it with JDBC because you aren't considering the real world operating environment of phones and portable devices. They often have flakey connectivity through buggy traffic rewriting proxies and insane firewalls. They're typically using a network transport layer that has high and variable packet loss rates and latencies that vary over many orders of magnitude in short spans of time. TCP really isn't great in this environment and particularly struggles with long lived connections.

The key benefit of a web service is that it:

  • Has short-lived connections with minimal state, so it's easy to get back to where you were when the device switches WiFi networks, to/from cellular, loses connectivity briefly, etc; and

  • Can pass through all but the most awful and draconian web proxies

You will routinely encounter problems with a direct JDBC connection. One challenge is reliably timing out dead connections, re-establishing sessions and releasing locks held by the old session (as the server may not decide it's dead at the same time the client does). Another is packet loss causing very slow operations, long-running database transactions, and consequent problems with lock durations and transactional cleanup tasks. You'll also meet every variety of insane and broken proxy and firewall under the sun - proxies that support CONNECT but then turn out to assume all traffic is HTTPs and mangle it if it isn't; firewalls with buggy stateful connection tracking that cause connections to fail or go to a half-open zombie state; every NAT problem you can imagine; carriers "helpfully" generating TCP ACKs to reduce latency, never mind the problems that causes with packet loss discovery and window sizing; wacky port blocking; etc.

Because everyone uses HTTP, you can expect that to work - at least, vastly more often than anything else does. This is particularly true now that common websites use REST+JSON communication style even in mobile web apps.

You can also write your web service calls to be idempotent using unique request tokens. That lets your app re-send modification requests without fear that it'll perform an action against the database twice. See idempotence and definining idempotence.

Seriously, JDBC from a mobile device might look like a good idea now - but the only way I'd even consider it would be if the mobile devices were all on a single high-reliably WiFi network under my direct control. Even then I'd avoid it for reasons of database performance management if I possibly could. You can use something like PgBouncer to pool connections among many devices at the server side so connection pooling isn't a big problem, but cleanup of lost and abandoned connections is, as is the tcp keepalive traffic required to make it work and the long stalled transactions from abandoned connections.

5
  • Ok, thanks. Subquestion: Can you explain why do you think it's slower over direct conn? Ok, WiFi or 3G, but the bottleneck is there because I need data on mobile device. Do you want to say that there is more data to transfer if I'm using a direct connection?
    – fenix
    Apr 6, 2013 at 17:45
  • 2
    @StevanPopov Your issue won't be bandwidth, it'll be long connection stalls caused by packet loss and/or switches of IP when the transport changes. With a stateless web service you can abandon the connection and make a new request if it's taking too long more easily than you can with a full JDBC connection, and it's much quicker to set up with fewer round trips. You can also have a web service collect up the output of several queries (or perform additional queries based on the result of a 1st one) and report all the results in a single result, reducing round trip latency costs. Apr 6, 2013 at 17:50
  • Thanks Craig, you've really convinced me, and thanks for free knowledge. It's hard to me to believe in that putting some bridge (in this case it is WS) is easier than to jump over the river. I'm using multiple limited mySQL accounts so I can monitor trough log files. How it can be done through WS if it's connects to db with the same account?
    – fenix
    Apr 6, 2013 at 18:00
  • @StevanPopov I'd suggest that as a new question. I don't really do MySQL much, more of a Pg guy. There probably are cases where direct JDBC is easier/better (there are exceptions to every rule), but in general a webservice based approach - with appropriate client side timeouts, retries and error management - will produce a more user-friendly result. Apr 6, 2013 at 18:23
  • @CraigRinger I'm a MySQL expert and I agree. What you say would apply to any stateful client/server protocol. E.g. I wouldn't choose to open an ftp connection from a mobile device either. Aug 29, 2021 at 15:35
9

I can think of a few reasons

  1. JDBC android driver support for your database.
  2. Connection pooling across various Android devices make it difficult to monitor and cap them.
  3. Result sets sent from the DB to android will consume a lot of bandwidth and battery power.
  4. Proxies usuall allow HTTP access to your device.
  5. Exposing your database directly to the client has security implications.

Web services can provide additional features on top of the JDBC connection like authentication / quality of service / authorization / conditional GET requests / error handling etc. JDBC cannot do any of these.

3
  • I've made the security argument myself before, but I'm not really convinced by it now. A properly designed permissions model inside the DB should be just as robust as access via authenticated web services. Sure, your DB might have remotely exploitable bugs like the nasty one just fixed in PostgreSQL 9.2 ... but so might your application server, in fact it's very likely with the insane complexity of modern appservers. Using a web service remains a very good idea for other reasons but I don't think the security argument holds water. Neither does bandwidth+power really; HTTP+JSON's no better. Apr 6, 2013 at 17:12
  • If you're using direct DB connections instead of an app server you don't get an additional target, just a different target. If you lock the DB away behind an intermediary appserver/webserver you can't limit the IPs that use the appserver running the web service either, nor place that on a private network. You've hidden one target and added another. I think web services are a better idea for all sorts of other reasons - but security, not so much. You do get better control of information leakage through a web service layer and that's one kind-of-security benefit to the approach. Apr 6, 2013 at 17:21
  • If you use X instead of Y then yes, some of my points are not applicable. I agree that the app layer and DB layer share security challenges equally at some level. The Postgres exploit and the web-server-hash-collision exploit come to mind. I was going to bring up authentication / authorization and information access, but I see you've already agreed that WS does a good job at securing those. We're on the same page. Apr 6, 2013 at 17:41
6

Besides all things Craig Ringer said, which I completely agree, JDBC has another problem: it will force to expose your database to the world. If you want android devices to access it, you will need to provide your app with database credentials, and the database will have to have public access.

Using a WebService or RESTful API is clearly the way to go to make your application secure.

0

Another option would be to use a database sync tool like SymmetricDS.

This would let you have say a Postgres database on your server, and a SQLite database on your tablet.

SymmetricDS would synchronize the databases over HTTP, when a connection is available. You don't have to sync the whole db of course, just the relevant parts.

(I am not affiliated with SymmetricDS)

1
  • 1
    Is there any simple example for that tool? Example for Android SQLite?
    – fenix
    Oct 12, 2013 at 14:45
0

TL;DR: It depends!

When creating a public domain / general app for the playstore kind of thing, I am mainly with my fellow responders. Opening your DB to "everyone" (especially when permissions are badly or not at all configured) is typically not a great idea!!

However(!), the story might be totally different, when you e.g. create something for internal use within the network boundaries of your company, like Android handheld devices for logistics, inventory, etc. In these cases I would even most of the time definately recommend going with JDBC or a similar direct connection. Reaons being:

  • One less point of failure
  • One less thing to maintain and keep up to date with your data-structure
  • One less thing to keep up and running, CI/CD, test, etc.

Which - im my humble opinion - can be worse than the (implement it once) effort of connection pooling, reestablishment, etc. (if it really becomes necesseary - be careful with premature optimization there).

But for public projects ... well, if they only ever require read access, I could possibly imagine it as well, or if there are only certain tables were you allow adding, but not delete or modifications. There are some tricks you could apply to make it still secure (allowing adds but not reads with id-secrets for a certain table, triggers, and general reads for other tables, etc.), but there is a lot to think and a lot to miss about these. So generally, I would say it is bad practice to allow your public domain client to get hold of your SQL connection. But still, don't let that hinder you to ask yourself (and understand) "why" and look at the specific situation. There might even be good cause/use for that. Especially since it is "less", which is also often better. It definately depends.

Just be careful and aware that (even if permissions are set correctly) a lot can be misused (and only little hindered), with a direct connection at your client. (Plus possible connection issues to be taken care of.)

As a sidenote: A lot of these considerations are relevant again with the use of technologies like GraphQL, which shares some similarities (however without connection issues and with a little bit more secure control).

Also features like row level security (RLS) go this route (e.g. in serverless apps) by moving security (from database or table level) to individual rules for rows in the database. Some level of authentication has to be implemented for that, typically allowing "anonymous" user/connection certain rights to login or read general posts. E.g., a rule could be to only allow edits to a row, if the user is the author of that post/entry (i.e. "tablename.authorId = @CURRENT_USER").

2
  • Good answer. Thanks for expanding on the discussion. Just curious - do you know if it's possible to use JDBC to connect to SQL Server but using Windows auth instead of SQL Server auth? Aug 31, 2023 at 21:53
  • Yes, with correct the connection string properties, i.e.: authenticationScheme=NTLM;integratedSecurity=true;domain=yourDomain
    – Levite
    Sep 4, 2023 at 12:36

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.