Does each queries create new connection in database
In most databases, each query does not necessarily create a new connection. Instead, a connection is typically established when the database is first connected to, and then reused for subsequent queries.
Here's how it usually works:
- Connection establishment: When your application (e.g., a web server, a script, or a program) connects to a database, a new connection is established. This involves creating a socket, authenticating the user, and setting up the communication channel.
- Query execution: When you send a query to the database, it is executed on the existing connection. The database server processes the query and returns the results to your application.
- Connection reuse: The connection remains open and is reused for subsequent queries, as long as the connection remains idle for a certain period of time (known as the "connection timeout"). This is done to improve performance and reduce the overhead of establishing a new connection.
However, there are some scenarios where a new connection might be created for each query:
- Connection pooling: Some databases, like Oracle, use connection pooling, where multiple connections are created and managed by the database server. In this case, each query might use a different connection from the pool.
- Connectionless protocols: Some databases, like MongoDB, use connectionless protocols, where each query is sent as a separate request, and a new connection is established for each query.
- Error handling: If an error occurs during query execution, the connection might be closed, and a new connection might be established for the next query.
- Database configuration: Some databases, like MySQL, allow you to configure the connection behavior. For example, you can set the
connect_timeout
parameter to control how long a connection remains idle before being closed.
In summary, while each query does not necessarily create a new connection, there are scenarios where a new connection might be created for each query. The specific behavior depends on the database system, connection pooling, and configuration settings.