2

I'm pretty green to DBMS and I'm required to write a Java program using JDBC to interact with an Access database file. I'm wondering if it's better practice, or even possible, to initialize the Connection in main and pass it to each method as needed (closing it after the program has run) or to open and close a new connection in each individual method.

Sorry if this is a repeat but none of the questions/answers on I've found on this have been conclusive.

PeterSon
  • 91
  • 7

2 Answers2

0

Opening a connection takes quite a long time. You should use the same connection through your program if there is no special reason to close it.

There is even a special technique called connection pooling, which allows re-using open connections in large applications, which improves the performance.

user5500105
  • 297
  • 2
  • 7
  • Well I don't know much about database access so I wouldn't know what a "special reason" might look like. – PeterSon Oct 29 '15 at 00:34
  • A special reason could be, for example, a connection error or database shutdown. – user5500105 Oct 29 '15 at 00:36
  • Gotcha, guess I'll just open and close it once in main since it's not like this program will ever be used in the wild. Thanks alot – PeterSon Oct 29 '15 at 00:56
0

I think creating a single connection object is a best way as you are decreasing the overhead for JVM for creating and garbage collecting an object. (Use try-with-resource. it will take care for closing of connection object automatically)

Shivang Agarwal
  • 1,825
  • 1
  • 14
  • 19