简体   繁体   中英

should i keep a database connection open in a servlet?

I am creating a simple blogging website just as a learning project using java servlets on tomcat.

There will be two pages: first page is a form to enter the subject and text for the blog, inserts them into a mysql database using jdbc.

second page is a page which fetches data from the database and displays it.

so I was wondering if instead of opening and closing the jdbc database connection in each page seperately, I should create a seperate class which keeps a connection open.

But, I dont want to instantiate it, and dont want to make it static.

Is there a way to do this?

also, is it a good practice and is it safe to keep a database connection open till the server is running ?

Think of a connection pool

Connection pools give you a whole bunch of advantages, but most of all they solve the problems of

  1. Making a real database connection is costly. The connection pool always has a few extra connections around and gives you one of those.
  2. If the connections fail, the connection pool knows how to open a new one
  3. Very important: every thread gets its own connection. This means that threading is handled where it should be: at the DB level. DBs are super efficient and can handle concurrent request with ease.
  4. Other stuff (like centralizing location of JDBC connect strings, etc.), but there are millions of articles, books, etc. on this

The following page on Tomcat's website describes how to connect Tomcat and mySQL in detail. You do not want to roll your own, there are too many DataSource pools already available that have been debugged and tried in production environments.

The main thing about using a pool is that a connection is not terminated when you call close, instead it is just returned to the pool. Therefore it is important to make sure that you close your resources in a try/finally block. Look here for a sample .

You're in a servlet, so you should use the connection pool the container provides. Your JNDI code will be completely normal except for how you obtain the connection. As far as I know, all servlet containers have connection pools.

You should install a JDBC datasource on Tomcat (see Tomcat JNDI Datasource HOW-TO ). Use the datasource to establish your JDBC connection, and you will have pooled connections.

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