简体   繁体   中英

Most efficient way to constantly communicate with a SQL database

So I'm working on a java program that will be constantly communicating with a SQL database. The user will input their own SQL database and I'd like the load of the database and the computer itself to be as low as possible. Every X (a time indicated by the user, most likely 5 seconds - 5 minutes) the program will check for a command from the database.

Method A

  • Every X connect to SQL and check if there are any commands
  • Close SQL connection

Or

Method B

  • Connect to SQL when first ran
  • Keep connection open and check for commands every X
  • Close connection before shutting down

I was wondering which method would be better.

When you have a program where you cannot estimate how frequently user access the database (eg searching the database, inserting new data, deleting old data) it is always a good idea to pool the connections, ie create a number of connection at startup and closing all connections in the pool before shutting down. Meanwhile connections are taken from the pool for querying the database and are released to the pool for further use. This approach avoids establishing and closing connections as they tend to be quite expensive. Keeping a connection alive is not a big deal and there a lot of connection pool libraries out there.

Given your use case you can estimate how often a database access will occur and since the timespan between two calls seem to be rather large, it is not necesarry to use pooling. Nonetheless it is a good practice.

The answer given refers to performance issues. From my point of view method B in addition allows for a better seperation of concerns. You have the whole connection stuff in one place and the business logic in another. No need to mix things up.

Finally the pool allows for monitoring the connections. It will give you control over how many connections should be opened at a maximum. This may be important, eg when a single task/query needs more time than the timespan between two calls which would result in more and more connections opened.

I hope this gives you some answers to your question.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM