Tuesday, August 25, 2009

Using MySQL User variables with Connection pooling

The point : MySQL user variables are connection specific. Period.
http://dev.mysql.com/doc/refman/5.1/en/user-variables.html

If your application is opening and closing a connection in the most simplest of fashion then you need not worry and you may use user defined variables as and when you please.

Come connection pooling and whole scenario is different.
In MySQL user-defined variables are connection-specific. You can store a value in a user-defined variable and then refer to it later. This enables you to pass values from one statement to another.

Now, when we use Hibernate/JPA or your custom db layer (with connection pooling) the underlying connection is not actually closed, it's committed & returned back to connection pool. As a result of which user defined variables once initialized will always be accessible and retain their previous value till the connection is active i.e. until application is shutdown or pool exhausts.

If you happen to use basic JDBC infrastructure (java.sql.*) wherein you could
explicitly close existing connection & open a new one, the variable would have
lost it's scope and reset for next time use.

So better to initializing a user defined variables in MySQL with NULL before using them any further. Unlike MSSQL it is not necessary to initialize a user defined variable, so it is always a matter of practice (good or bad).

No comments:

Post a Comment