Question

Is it possible to get persistent connections with the MySQL C API, like those PHP provides? If so, how?

Was it helpful?

Solution

The MySQL C API doesn't have a persistent connection feature because it doesn't need it. All connections you create through it are persistent. That is, they persist as long as your program runs unless you go and actively close them or the server drops them.

The only reason PHP needs persistent connections is that it's an artifact of the way HTTP works. PHP was originally a CGI program, so the web server would restart everything for each HTTP request, including any DB connections. This is very time consuming, so they created mod_php, which almost everyone using PHP uses now. The stateless nature of HTTP still requires that your PHP script restart on each request, but because mod_php stays loaded in the Apache instance, it can do things like hold MySQL DB connections open, for use by the next PHP script that needs it.

All of this begs the question, why do you believe you need persistent DB connections? Are you restarting your C program each time it's needed? If so, fixing that is probably what you need to be doing instead of looking for "missing" C API features. If you were writing a web application in C, for example, you could rework it as an Apache module, just as the standalone CGI PHP became mod_php.

But, always remember:

"The First Rule of Program Optimization: Don't do it. The Second Rule of Program Optimization (for experts only!): Don't do it yet."

— Michael A. Jackson

Optimizing before you have benchmarked and profiled your program is foolishness. Show us your design and your measurements, then ask what can be done. Don't go asking for technical fixes first. A design fix might help a lot more.

OTHER TIPS

Sure -- by not closing the connection. All that PHP's "persistent connections" do is keep the connection open and reuse it for subsequent script executions.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top