Win a copy of Design for the Mind this week in the Design forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

checking valid database connection

 
Phil Chuang
Ranch Hand
Posts: 251
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
How would I test out if a database location, name, username, password are valid for a database?
like making sure this is valid during a DB connect:
"jdbc:mysql://"+DBLocation+"/"+DBName+"?user="+username+"&password="+password";
 
Dirk Schreckmann
Sheriff
Posts: 7023
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You might use DriverManager.getConnection(String url, String user, String password) and catch the possible SQLException if a database access error (like invalid password) occurs. I'm not sure if there is a cleaner way to check for invalid account information than to simply try to use the account information (and handle any problems).
 
Phil Chuang
Ranch Hand
Posts: 251
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I tested it out, and getConnection doesn't seem to return any errors with bad information. I just set up a boolean method to try to "show tables" and return false on any exceptions. Dirty, but it should work.
 
Dirk Schreckmann
Sheriff
Posts: 7023
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I just double checked that I do indeed get a connection failure (in the form of an SQLException) when I try to connect to a MySQL database with invalid user information. The error message reads:
General error: Access denied for user: 'somebody@somewhere' to database 'someDatabase'
I'm not sure why your experience would differ.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic