I have a database with several registered users that acess the database throught a java app using jdbc. I've read elsewhere that connections should be opened and closed in the shortest amount of time possible, most of the time in the same try block as the statment or query you're executing. This however implies that i should store the user and password in the program memory, and use it repeatedly to create new connections; but aren't there security concerns in storing a password in the program memory? How should make new connections to the database?
-
Use a database connection pool. This piece of software will initialize the connections and close them for you. – Luiggi Mendoza Mar 27 '15 at 04:33
2 Answers
I assume your question is NOT about how to code DB connection.
It really depends on whether your users have id registered with the database or you only have one id (non-human) for program connection and serve all users. If the former, you can somehow prompt the user to input password once, store it in variable, use the variable for connect, disconnect after use, reconnect/disconnect if needed. The password is only "stored" in memory on the fly and no longer exist after your program ends, so it is safe.
If it is the later, then you better have your program run in a web/servlet server, and, like Luiggi said, use connection pool. In this case, the connection password will be coded in some configuration file and accessible only by the administrator of the server. If you can't have such server, you have to go back to solution in above paragraph and register all your users in the DB, each with own id and password.
Hope it helps.

- 400
- 1
- 9
I've read elsewhere that connections should be opened and closed in the shortest amount of time possible
A transaction should be done in the shortest amount of time possible. Constantly opening and closing connections would incur a lot of (network) overhead.
But if you use a connection pool, opening and closing connections only results in taking a connection from the pool and releasing a connection back into the pool. In this case, opening and closing a connection should be done as fast as possible so that other processes/threads can re-use the connection. The connection pool itself manages the actual opening and closing of (network) connections for you, along with other useful features like ensuring you close result-sets, close prepared statements, keeping connections healthy, etc..
Using a connection pool is beneficial whether database connections are used from a client-app or application server. I have explained this in a previous answer.