Db.php
2.6 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
<?php
namespace Lib;
/**
* db
* @author:dc
* @time 2023/2/13 15:03
* Class Db
* @package Lib
*/
class Db {
use DbQuery;
/**
* @var \Lib\Db
*/
static $instance;
/**
* @return mixed
* @author:dc
* @time 2023/2/13 9:12
*/
public function getClient(){
if(!$this->client){
$this->connect();
}
try {
// 判断是否链接中
$status = $this->client->getAttribute(\PDO::ATTR_CONNECTION_STATUS);
if($status === null || $status === false){
$this->connect();
}
}catch (\Throwable $e){
$this->connect();
}
return $this->client;
}
private $host='';
private $prot='';
private $user='';
private $pwd='';
private $database='';
public function __construct($host='',$database='',$user='',$pwd='',$prot='')
{
$this->host = $host ? $host : DB_HOST;
$this->prot = $prot ? $prot : DB_PORT;
$this->user = $user ? $user : DB_USER;
$this->pwd = $pwd ? $pwd : DB_PASSWORD;
$this->database = $database ? $database : DB_DATABASE;
// $this->connect();
}
/**
* 连接sql
* @author:dc
* @time 2023/3/23 9:14
*/
public function connect(){
$tryNum = 0;
DBPOOLCONNECTFOR:
try {
$this->client = new \PDO(
'mysql:charset=utf8mb4;dbname='.$this->database.';host='.$this->host.';port='.$this->prot,
$this->user,
$this->pwd,
[
\PDO::ATTR_DEFAULT_FETCH_MODE => \PDO::FETCH_ASSOC,
\PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES 'utf8mb4'",
\PDO::ATTR_ERRMODE => \PDO::ERRMODE_EXCEPTION,
]
);
}catch (\Throwable $e){
// 重新链接3次
if($tryNum < 3){
$tryNum++;
goto DBPOOLCONNECTFOR;
}
logs($e->getMessage().$e->getTraceAsString());
}
}
/**
* @return Db
* @author:dc
* @time 2023/2/13 9:39
*/
public static function instance(){
if(empty(static::$instance)){
static::$instance = new Db();
}
// if(!static::$instance->ping()){
// static::$instance->close();
//
// static::$instance = new Db();
// }
return static::$instance;
}
/**
* 结束
*/
public function __destruct(){
$this->close();
}
public function close(){
$this->client = null;
}
}