0

My application-server has a connection to a MySQL database. This connection is open 24/7.

Lets say my internet were to crash, or I were to block the port 3306.

Will JDBC throw an error? And if not, how should I be handling this kind of problem?

The reason I'm asking this is because I've had cases before where the MySQL connection randomly stopped working, but wasn't closed, which caused clients to time out.

Elite_Dragon1337
  • 348
  • 2
  • 13
  • 1
    You could just pull the plug and see what happens... :-) – thebjorn Feb 12 '14 at 19:40
  • http://stackoverflow.com/questions/2983248/com-mysql-jdbc-exceptions-jdbc4-communicationsexception-communications-link-fai – kosa Feb 12 '14 at 19:41
  • Easiest way to find out: Build up a connection and pull the cable. The worst case, what you already found out, is that your connection times out. The Database system will abort the transaction and - in case it's on its side - maybe rollback. – Sebastian Höffner Feb 12 '14 at 19:41
  • A frequent problem is network devices silently dropping tcp/IP connections. This is why JDBC pools have mechanism for detecting stale connections. Your application server should have that. – Thorbjørn Ravn Andersen Feb 12 '14 at 19:42

2 Answers2

1

You will get a MySQLNonTransientConnectionException or CommunicationsException. Typically, for program safety you either want to:

  • Open/close connections as necessary

  • Re-open when connection is closed

I recommend the former personally, especially when the database is user-specified (some mysql setups have a connection timeout).

Edit:

I did seem to forget to mention connection pools, per @ThorbjørnRavnAndersen , but that is also a viable solution. I personally don't do that myself, using an instantiable SQL connection per threaded operation.

Rogue
  • 11,105
  • 5
  • 45
  • 71
0

Personally, I throw any database calls into try/catch blocks, because there's always the potential for issues to arise. You'll want to set some default values in the catch block, and if it happens to land on these defaults for whatever reason, display the end user some sort of (ideally pretty) error message.

Running a SQL query isn't always guaranteed to pull back any sort of results either...any number of things could go wrong - the server could be down, the connection could be so saturated that it's not able to pull the results in a timely manner, it could be sitting in the dead center of a backup of sorts too....These things have to always be accounted for, that's why I recommend doing it the way described above.

Lastly, to answer your question, yes, JDBC will in fact throw an error - under any of these circumstances.

user2366842
  • 1,231
  • 14
  • 23