How to implement a php framework series [6] mysql database,
Considerations for implementing a mysql database Encapsulation
Ease of use
Use a direct SQL statement. As long as SQL statements are written, there will be no other learning costs.
The dba-assisted encapsulation class provided by the uctphp framework is easy to use.
Do you need to display initialization and connection to the database before use, of course, no.
The database is not connected or even a new db object until the first SQL statement is executed.
Dba will connect to the database and perform initialization character encoding at the right time.
Query statement. The new query constructor is not required and does not provide chain operations, which is complex and inefficient.
Dba provides the following query auxiliary functions.
| 123456789101112 |
// Read a valueDba::readOne($sql);// Read a rowDba::readRowAssoc($sql);// Read all rowsDba::readAllAssoc($sql);// Read the first column of all rowsDba::readAllOne($sql); // In actual business scenarios, partial data is often read by page.// You can return the data content and total number of data records of a specified page number as long as one function.Dba::readCountAndLimit($sql, $page, $limit); |
Ps: The preceding functions provide a map function to process each row of the returned array.
Write statement. Why do we need to distinguish between read and write? Obviously, it can be extended to control read/write splitting, dual-write, and other functions.
Today, with a variety of cloud databases and database middleware, implementing at the database layer is a better choice.
| 123456789101112131415 |
Dba::write($sql); /* Directly insert or update an array in the kv formatValues are automatically escaped and array-type values are supported. Use addslashes or mysql_real_escape_string to ensure the security of SQL statements.*/Dba::insert($table, $insert); Dba::update($table, $update, $where); /* It is more efficient to insert data in batches. Of course, too many rows should be inserted in batches using array_chunk.*/Dba::insertS($table, $inserts); |
2. Transactions
Use pdo to support transactions
| 123 |
Dba::beginTransaction();Dba::commit();Dba::rollBack(); |
3. Long Running
In some scenarios that require long running, such as the swoole service and backend worker, database connection times out.
When the database connection times out, the dba automatically tries to reconnect.