简体   繁体   English

mysql.h持久连接

[英]mysql.h persistent connection

Is it possible to get persistent connections with the MySQL C API, like those PHP provides ? 是否有可能像PHP所提供的那样与MySQL C API保持持久连接? If so, how? 如果是这样,怎么办?

The MySQL C API doesn't have a persistent connection feature because it doesn't need it. MySQL C API没有持久连接功能,因为它不需要它。 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需要持久连接的唯一原因是它是HTTP工作方式的产物。 PHP was originally a CGI program , so the web server would restart everything for each HTTP request, including any DB connections. PHP最初是CGI程序 ,因此Web服务器将为每个HTTP请求重新启动所有功能,包括任何数据库连接。 This is very time consuming, so they created mod_php , which almost everyone using PHP uses now. 这非常耗时,因此他们创建了mod_php ,现在几乎所有使用PHP的人都使用它。 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. HTTP的无状态本质仍然要求您的PHP脚本在每次请求时都重新启动,但是由于mod_php保持加载在Apache实例中,因此它可以执行诸如保持MySQL DB连接打开以供需要它的下一个PHP脚本使用的操作。

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? 您是否在需要时重新启动C程序? If so, fixing that is probably what you need to be doing instead of looking for "missing" C API features. 如果是这样,则可能需要解决此问题,而不是寻找“缺失的” C API功能。 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. 例如,如果您使用C编写Web应用程序,则可以将其作为Apache模块进行重新处理 ,就像独立的CGI PHP成为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. 设计修复可能会提供更多帮助。

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. PHP的“持久连接”所做的只是保持连接打开,并将其重用于以后的脚本执行。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM