Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is a Connection in JDBC?

What is a Connection Object in JDBC ? How is this Connection maintained(I mean is it a Network connection) ? Are they TCP/IP Connections ? Why is it a costly operation to create a Connection every time ? Why do these connections become stale after sometime and I need to refresh the Pool ? Why can't I use one connection to execute multiple queries ?

like image 630
Geek Avatar asked May 08 '09 06:05

Geek


People also ask

What is JDBC connection?

JDBC (Java Database Connectivity) is the Java API that manages connecting to a database, issuing queries and commands, and handling result sets obtained from the database. Released as part of JDK 1.1 in 1997, JDBC was one of the earliest libraries developed for the Java language.

What is connection and statement in JDBC?

JDBC makes it possible to do establish a connection with a data source, send queries and update statements, and process the results. Simply, JDBC makes it possible to do the following things within a Java application: Establish a connection with a data source. Send queries and update statements to the data source.

What is a connection URL?

A JDBC URL provides a way of identifying a database so that the appropriate driver recognizes it and connects to it. In the Derby documents, a JDBC URL is referred to as a database connection URL.


2 Answers

These connections are TCP/IP connections. To not have to overhead of creating every time a new connection there are connection pools that expand and shrink dynamically. You can use one connection for multiple queries. I think you mean that you release it to the pool. If you do that you might get back the same connection from the pool. In this case it just doesn't matter if you do one or multiple queries

The cost of a connection is to connect which takes some time. ANd the database prepares some stuff like sessions, etc for every connection. That would have to be done every time. Connections become stale through multiple reasons. The most prominent is a firewall in between. Connection problems could lead to connection resetting or there could be simple timeouts

like image 186
Norbert Hartl Avatar answered Oct 07 '22 23:10

Norbert Hartl


To add to the other answers:

Yes, you can reuse the same connection for multiple queries. This is even advisable, as creating a new connection is quite expensive.

You can even execute multiple queries concurrently. You just have to use a new java.sql.Statement/PreparedStatement instance for every query. Statements are what JDBC uses to keep track of ongoing queries, so each parallel query needs its own Statement. You can and should reuse Statements for consecutive queries, though.

like image 27
sleske Avatar answered Oct 07 '22 23:10

sleske