# RapidDB 轻量级数据库操作组件* 支持事务嵌套* PDO支持* JSON支持* 类的实例集合支持* 轻量级* 可以轻易和其他框架整合* 多数据库多连接支持##使用方式###通过composer安装```$ composer require shiwolang/db```###通过git地址```http://git.oschina.net/shiwolang/RapidDB```###初始化连接**暂仅支持mysql和sqlite**#####单个连接情景```phpDB::init([ 'database_type' => 'mysql', 'database_name' => 'dbname', 'server' => 'localhost', 'username' => 'username', 'password' => 'yourpass', 'charset' => 'utf8']);```#####多个连接情景```phpDB::init([ 'database_type' => 'mysql', 'database_name' => 'dbname', 'server' => 'localhost', 'username' => 'username', 'password' => 'yourpass', 'charset' => 'utf8'], "connection1");```#####PDO设置初始化 单个连接情景```phpDB::init($PDO);```#####PDO设置初始化 多个连接情景```phpDB::init($PDO, "connection1");```###获取数据库连接---------------------------------------#####单个连接情景```phpDB::connection();```#####多个连接情景```phpDB::connection("connection1");```###添加数据(单表)---------------------------------------```php$lastInsertId = DB::connection()->insert("content", [ "title" => "title1", "content" => "content1", "time" => time()]);```###删除数据(单表)---------------------------------------```php$lastInsertId = DB::connection()->delete("content", "id = :id", [":id" => 1]);```###修改数据(单表)---------------------------------------```php$lastInsertId = DB::connection()->update("content", [ "title" => "title1", "content" => "content1", "time" => time()],"id = :id", [":id" => 1]);```###查询数据---------------------------------------**请注意在使用limit的时候的数值务必为整数int型!!**```phpDB::connection()->query("SELECT * FROM content where title = 'title1' LIMIT 10")->all();DB::connection()->query("SELECT * FROM content WHERE title = :title LIMIT :limit", [ ":title" => "title1", ":limit" => 10])->all();DB::connection()->query("SELECT * FROM content WHERE id = ? LIMIT ?", ["title1", 10])->all();```####设置获取模式#####设置为数组的获取方式(默认方式)```phpDB::connection()->query("SELECT * FROM content where title = 'title1' LIMIT 10")->all();```#####设置为类的实例集合的获取方式```phpDB::connection()->query("SELECT * FROM content where title = 'title1' LIMIT 10")->bindToClass(Content::class)->all();DB::connection()->query("SELECT * FROM content where title = 'title1' LIMIT 10")->all(Content::class);```#####将每行的列作为参数传递给指定的函数,并返回调用函数后的结果的获取方式```phpDB::connection()->query("SELECT * FROM content where title = 'title1' LIMIT 10")->all(function($title, $content, $time){ return [ "title" => $title, "content" => $content, "time" => date("Y-m-d H:i:s", $time) ];});```#####按相关的结果集中获取下一行数组获取方式```phpDB::connection()->query("SELECT * FROM content LIMIT 10")->each(function ($row) { print_r($row);});```类的实例获取方式```phpDB::connection()->query("SELECT * FROM content LIMIT 10")->each(function ($row) { print_r($row);}, Content::class);```#####JSON格式数据数组获取方式的json```phpDB::connection()->query("SELECT * FROM content LIMIT 10")->json();```类的实例集合获取方式的json **!!请注意!! DB::json(&$fetchResult = null, $className = null, $args = []) 第一个形参为返回的结果集,并不是绑定的类名!!**```phpDB::connection()->query("SELECT * FROM content LIMIT 10")->json($data, Content::className());```**!!注!!**json数据获取中当获取方式为对象集合的方式时,支持数据自动格式化,可以使用@json注解来注解类中的一个公共方法,对应的json键名为这个方法的首字符小写的[去掉get字符后(如果含有)]方法名称;同样可以实现ObjectContainerInterface和\JsonSerializable 接口并使用Statement::setJsonObjectContainerClassName($jsonObjectContainerClassName)进行对象集合容器的自定义设置###事务的支持-----------------------**此功能依赖数据事务功能**#####事务使用声明方式```php$db = DB::connection();$db->beginTransaction();try { $lastInsertId = $db->insert("content", [ "title" => "title1", "content" => "content1", "time" => time() ]); $db->commit();} catch (\Exception $e) { $db->rollBack(); throw $e;}```#####事务使用声明方式支持无限级嵌套```php$db = DB::connection();$db->beginTransaction();try { try { $lastInsertId = $db->insert("content", [ "title" => "title1", "content" => "content1", "time" => time() ]); $db->commit(); } catch (\Exception $e) { $db->rollBack(); throw $e; } $lastInsertId = $db->insert("content", [ "title" => "title2", "content" => "content2", "time" => time() ]); $db->beginTransaction(); try { $lastInsertId = $db->insert("content", [ "title" => "title3", "content" => "content3", "time" => time() ]); $db->commit(); } catch (\Exception $e) { $db->rollBack(); throw $e; } $db->commit();} catch (\Exception $e) { $db->rollBack(); throw $e;}```#####事务使用回调函数方式,支持无限级嵌套```phpDB::connection()->transaction(function () { DB::connection()->transaction(function () { DB::connection()->insert("content", [ "title" => "title1", "content" => "content1", "time" => time() ]); } }); DB::connection()->insert("content", [ "title" => "title2", "content" => "content2", "time" => time() ]); DB::connection()->transaction(function () { DB::connection()->insert("content", [ "title" => "title3", "content" => "content3", "time" => time() ]); } }); }});```###执行记录查询-----------------------#####获取所有执行记录```phpDB::connection()->query("SELECT * FROM content LIMIT 1")->all();DB::connection()->query("SELECT * FROM content WHERE title = :title LIMIT :limit", [ ":title" => "title1", ":limit" => 10])->all();;print_r(DB::connection()->getLog());```#####单条未执行的sql```php$sql = DB::connection()->query("SELECT * FROM content WHERE title = :title LIMIT :limit", [ ":title" => "title1", ":limit" => 10], true);```##附录#####Content类```phpclass Content{ private $id; private $title; private $content; /** * @return mixed */ public function getId() { return $this->id; } /** * @param mixed $id */ public function setId($id) { $this->id = $id; } /** * @return mixed */ public function getTitle() { return $this->title; } /** * @param mixed $title */ public function setTitle($title) { $this->title = $title; } /** * For json formater * @json * @return mixed */ public function getContent() { return $this->content . "_nihao"; } /** * @param mixed $content */ public function setContent($content) { $this->content = $content; } public function __get($name) { $getter = 'get' . self::camelName($name); if (method_exists($this, $getter)) { return $this->$getter(); } throw new \Exception('Getting unknown property: ' . get_class($this) . '::' . $name); } public function __set($name, $value) { $setter = 'set' . self::camelName($name); if (method_exists($this, $setter)) { $this->$setter($value); return; } throw new \Exception('Setting unknown property: ' . get_class($this) . '::' . $name); } protected static function camelName($name, $ucfirst = true) { if (strpos($name, "_") !== false) { $name = str_replace("_", " ", strtolower($name)); $name = ucwords($name); $name = str_replace(" ", "", $name); } return $ucfirst ? ucfirst($name) : $name; }}```#####数据库创建语句```sqlCREATE TABLE `content` ( `id` int(11) NOT NULL AUTO_INCREMENT, `title` varchar(255) DEFAULT NULL, `content` varchar(255) DEFAULT NULL, `time` int(10) DEFAULT NULL, PRIMARY KEY (`id`)) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8```

What’s still popular is the ease of use, flexibility and a strong ecosystem. 1) Ease of use and simple syntax make it the first choice for beginners. 2) Closely integrated with web development, excellent interaction with HTTP requests and database. 3) The huge ecosystem provides a wealth of tools and libraries. 4) Active community and open source nature adapts them to new needs and technology trends.

PHP and Python are both high-level programming languages that are widely used in web development, data processing and automation tasks. 1.PHP is often used to build dynamic websites and content management systems, while Python is often used to build web frameworks and data science. 2.PHP uses echo to output content, Python uses print. 3. Both support object-oriented programming, but the syntax and keywords are different. 4. PHP supports weak type conversion, while Python is more stringent. 5. PHP performance optimization includes using OPcache and asynchronous programming, while Python uses cProfile and asynchronous programming.

PHP is mainly procedural programming, but also supports object-oriented programming (OOP); Python supports a variety of paradigms, including OOP, functional and procedural programming. PHP is suitable for web development, and Python is suitable for a variety of applications such as data analysis and machine learning.

PHP originated in 1994 and was developed by RasmusLerdorf. It was originally used to track website visitors and gradually evolved into a server-side scripting language and was widely used in web development. Python was developed by Guidovan Rossum in the late 1980s and was first released in 1991. It emphasizes code readability and simplicity, and is suitable for scientific computing, data analysis and other fields.

PHP is suitable for web development and rapid prototyping, and Python is suitable for data science and machine learning. 1.PHP is used for dynamic web development, with simple syntax and suitable for rapid development. 2. Python has concise syntax, is suitable for multiple fields, and has a strong library ecosystem.

PHP remains important in the modernization process because it supports a large number of websites and applications and adapts to development needs through frameworks. 1.PHP7 improves performance and introduces new features. 2. Modern frameworks such as Laravel, Symfony and CodeIgniter simplify development and improve code quality. 3. Performance optimization and best practices further improve application efficiency.

PHPhassignificantlyimpactedwebdevelopmentandextendsbeyondit.1)ItpowersmajorplatformslikeWordPressandexcelsindatabaseinteractions.2)PHP'sadaptabilityallowsittoscaleforlargeapplicationsusingframeworkslikeLaravel.3)Beyondweb,PHPisusedincommand-linescrip

PHP type prompts to improve code quality and readability. 1) Scalar type tips: Since PHP7.0, basic data types are allowed to be specified in function parameters, such as int, float, etc. 2) Return type prompt: Ensure the consistency of the function return value type. 3) Union type prompt: Since PHP8.0, multiple types are allowed to be specified in function parameters or return values. 4) Nullable type prompt: Allows to include null values and handle functions that may return null values.


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

MantisBT
Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

SAP NetWeaver Server Adapter for Eclipse
Integrate Eclipse with SAP NetWeaver application server.

MinGW - Minimalist GNU for Windows
This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

PhpStorm Mac version
The latest (2018.2.1) professional PHP integrated development tool

Atom editor mac version download
The most popular open source editor