因为有些小的数据, 不想存在mysql太乱了, 所以想到了用 sqLite ,
查了一下, php连接sqLite 很简单, 而且 liunx 就内置了 sqLite 数据库,
直接在liunx输入 sqLite3 即可进入交互;
注意, 退出时候,需要先按.quit 才能退出…
新建数据库: sqlite3 tm.db;
然后使用php操作数据库!
首先我想到了万能的conmposer, 找到了一个php的ORM类!
so easy 啊
$database = new medoo([
'database_type' => 'sqlite',
'database_file' => 'my/database/path/database.db'
]);
$database->insert("account", [
"user_name" => "tianming",
"email" => "iyahe@qq.com"
]);
1
2
3
4
5
6
7
8
9
$database=newmedoo([
'database_type'=>'sqlite',
'database_file'=>'my/database/path/database.db'
]);
$database->insert("account",[
"user_name"=>"tianming",
"email"=>"iyahe@qq.com"
]);
注意: 这里因为命名空间的问题, 我是直接下载了文件, 没有使用composer, 类里面的 PDO 要改为 \PDO, 否则会找不到 PDO 扩展而报错
但是后来, 无意间看到
ThinkPHP内置了抽象数据库访问层,把不同的数据库操作封装起来,我们只需要使用公共的Db类进行操作,而无需针对不同的数据库写不同的代码和底层实现,Db类会自动调用相应的数据库驱动来处理。数据库抽象访问层基于PDO方式,目前内置包含了Mysql、SqlServer、PgSQL、Sqlite等数据库的支持。
…. 原来thinkphp早已经支持了.
那就查文档吧!
// 多个数据库配置
'db_speak' => [
// 数据库类型
'type' => 'sqlite',
'database' => APP_ROOT .'/public/db/speak.db', // 相对于入口文件的数据库文件路径
'prefix' => '',
'debug' => true
],
1
2
3
4
5
6
7
8
// 多个数据库配置
'db_speak'=>[
// 数据库类型
'type'=>'sqlite',
'database'=>APP_ROOT.'/public/db/speak.db',// 相对于入口文件的数据库文件路径
'prefix'=>'',
'debug'=>true
],
在database.php 里面新增一条数据库配置!
使用的时候 Db::connect(‘db_speak’) ->table($table)->xxx();
接下来的操作就是thinkphp内置orm的使用习惯了,
但是
SQLSTATE[HY000]: General error: 8 attempt to write a readonly database
报错了, 原来是数据库没有读写权限,给speak.db给777权限!
又报错
General error: 14 unable to open database file
因为 打开数据库文件时,还会自动生成一个临时文件。服务器不仅需要对数据库文件可写,而且要对包含该数据库文件的文件夹可写。
所以要给放置数据库的db目录给777权限!
然后
namespace app\index\controller;
use app\action;
use think\Db;
class Index extends action
{
public function index(){
$this->redirect('http://blog.he29.com?come=api');
}
public static function db ($table) {
return Db::connect('db_speak')
->table($table);
}
public function welcome(){
//$list = self::db('list')->find();
//p($list);
for ($i = 0; $i < 110; $i++) {
$result = self::db('list')->insertGetId([
'text' => rand(0,9),
'time'=> getStrtime()
]);
p($result);
}
//$list = self::db('list')->paginate(10);
//p($list);
}
}
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
namespaceapp\index\controller;
useapp\action;
usethink\Db;
classIndexextendsaction
{
publicfunctionindex(){
$this->redirect('http://blog.he29.com?come=api');
}
publicstaticfunctiondb($table){
returnDb::connect('db_speak')
->table($table);
}
publicfunctionwelcome(){
//$list = self::db('list')->find();
//p($list);
for($i=0;$i<110;$i++){
$result=self::db('list')->insertGetId([
'text'=>rand(0,9),
'time'=>getStrtime()
]);
p($result);
}
//$list = self::db('list')->paginate(10);
//p($list);
}
}
100 条数据顺利插入成功了, 分页数据也加载出来了!
以后就可以无忧无虑的使用sqlite数据库了!