通过函数与对象访问数据库,有什么区别?
因此,在我的应用程序中,我通过函数名为 db_connect();。很简单,它提供了必要的登录信息并通过 mysql_connect 和 mysql_select_db 打开数据库连接。
现在我正在工作,我发现首席程序员使用 PDO。想要。然而,它看起来或多或少像我以前使用的同一东西的面向对象版本。
那么,按照我以前的方式做,或者编写一个带有自动连接数据库的构造函数的“db”类,有什么区别呢?
在这两种情况下,我都必须连接到数据库/创建一个新对象,无论哪种情况,都会占用一行。
它是一个抽象库来抽象数据库连接的本质吗?
我唯一能想到的是,OO 版本中有一个析构函数,这意味着我不必在“db_close()”中编写代码...
Edu-ma-cate 我! (请)
Possible Duplicate:
PHP PDO vs normal mysql_connect
So in my application, I accessed the database via a function named db_connect();. Quite simply, it fed the requisite login information and opened a database connection via mysql_connect and mysql_select_db.
Now that I'm working, I have found that the lead programmer uses PDO. Fancy. However, it looks more or less like an object-oriented version of the same thing I used to use.
So what's the difference between doing it the way I used to, or writing a class "db" with a constructor that automatically connects to the database?
In both cases, I'd have to connect to the db/create a new object, which, in either case, takes up one line.
Is it a fancy library to abstract away the nitty-gritty of database connections?
The only thing I can think of is that there's a destructor in the OO version, which means I wouldn't have to code in a "db_close()"...
Edu-ma-cate me! (Please'm)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您的数据库库是函数式的还是面向对象的,本身并不重要,但 PDO 非常现代,并且比普通的旧式 mysql_connect() 和 consorts 具有许多优势,最重要的是使 SQL 进行参数化查询注射是不可能的。
此外,PDO 支持更多的数据库平台。
从体系结构的角度来看,OOP 方法也很有意义,它不仅仅是装饰:您创建一个 PDO 对象,它是您的数据库连接。多个对象=多个连接。将结果集包装到一个对象中 - 提供所有的函数来获取行、跳过、倒带等......也是非常合乎逻辑的。
如果我要为新项目选择数据库包装器,我肯定会选择 PDO,而不是
mysql_*()
。Whether your database library is functional or object oriented is not really relevant per se, but PDO is very modern and has a number of advantages over plain old
mysql_connect()
and consorts, most importantly parametrized queries that make SQL injections impossible.Also, PDO supports a whole lot more database platforms.
From an architectural perspective, the OOP approach also makes sense, it's more than just decoration: You create a PDO object, which is your database connection. Multiple objects = multiple connections. Wrapping a result set into an object - providing all the functions to fetch rows, skip, rewind, etc.... is also very logical.
If I were to choose a database wrapper for a new project, I'd definitely go with PDO over
mysql_*()
.