-
Notifications
You must be signed in to change notification settings - Fork 4
/
db.php
71 lines (57 loc) · 2.12 KB
/
db.php
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
<?php
namespace Flylink\DHT;
use PDO;
use PDOException;
use PDOStatement;
/**
* Simlpe PDO wrapper.
*
* @author JhaoDa <jhaoda@gmail.com>
*/
class DB {
private $text;
/** @type PDO */
private $pdo;
/** @type PDOStatement */
private $statement;
public function __construct() {
try {
/*
$this->pdo = new PDO($this->options['DSN'], $this->options['username'], $this->options['password']);
*/
$this->pdo = new PDO('sqlite:/db/dht.sqlite');
$this->pdo->setAttribute(PDO::ATTR_PERSISTENT, true);
$this->pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$this->pdo->setAttribute(PDO::ATTR_EMULATE_PREPARES, true);
$this->pdo->query('PRAGMA journal_mode=OFF');
#this->pdo->query('PRAGMA temp_store=OFF');
$this->pdo->query('create table if not exists dht_info (cid char(39) primary key, ip varchar(15) not null, port int not null, conn_count int not null default 0, user_agent varchar(256), live int not null default 0, last_time datetime default current_timestamp);');
} catch (PDOException $e) {
die('Failed to create PDO instance' .$e->getMessage());
}
}
public function query($text, $params = []) {
try {
$this->prepare($text);
$this->statement->execute(empty($params) ? null : $params);
$result = $this->statement->fetchAll(PDO::FETCH_ASSOC);
$this->statement->closeCursor();
return $result;
} catch(PDOException $e) {
die('Failed to execute the SQL statement: '.$e->getMessage());
}
}
public function execute($text, $params = []) {
try {
$this->prepare($text);
$this->statement->execute(empty($params) ? null : $params);
return $this->statement->rowCount();
} catch(PDOException $e) {
die('Failed to execute the SQL statement: '.$e->getMessage());
}
}
private function prepare($text) {
$this->text = str_replace('{table}', 'dht_info', $text);
$this->statement = $this->pdo->prepare($this->text);
}
}