-
- /**
- * mysql read and write separation
- * edit: bbs.it-home.org
- */
- class db
- {
- public function __construct($sql)
- {
- $chesr = strtolower(trim($sql));
- //Judge sql If the statement has the select keyword, it will connect to the reading database, otherwise it will connect to the writing database
- if(substr($chestr,0,6)=='select')
- {
- echo 'I am using select db..< br>';
- $link = mysql_connect("127.0.0.1:3306", "root", "") or die("Could not connect: " . mysql_error());
- mysql_select_db("test");
- $ result = mysql_query($sql);
- while ($row = mysql_fetch_array($result, MYSQL_NUM))
- {
- printf("%s %s", $row[0],$row[1]);
- }
- echo mysql_get_host_info($link).mysql_get_server_info($link).mysql_get_proto_info($link).mysql_get_client_info().'
';
- }
- else
- {
- echo 'I am using insert db..
';
- $link = mysql_connect("127.0.0.2:3306","root","") or die("Could not connect: " . mysql_error());
- mysql_select_db("test");
- $result = mysql_query($sql);
- echo @mysql_affected_rows($result);
- echo mysql_get_host_info($link).mysql_get_server_info($link).mysql_get_proto_info($link).mysql_get_client_info().'
'; }
-
- }
- }
-
- $d = new db(" update `users` set `select`='fasdf' where `id` =1");
- $d2 = new db(" SELECT * from `users`");
-
Copy the code
Attached is the explanation of database reading and writing sharing.
The separation of reading and writing in the database can effectively reduce the pressure on the database.
The architecture of one master database and multiple slave databases to achieve separation of reading and writing is a commonly used solution.
The master database provides write operations, and the slave database provides read operations.
In fact, dispersing the pressure on the database does not necessarily require separation of reading and writing, but separation of reading and writing still has many benefits of its own.
for example:
1. Conducive to the implementation of load balancing of the database.
2. It is conducive to realizing hot backup of master-slave database. If it is not separated, then you need to consider a two-way hot backup strategy.
The configuration of this is more complicated, and it is also more troublesome when problems occur.
3. Helps maintain high availability of the database, especially in a database cluster environment.
4. Finally, after realizing the separation of reading and writing, you will have more confidence in the query speed and stability of mysql.
|