本文共 2135 字,大约阅读时间需要 7 分钟。
在 database.php 文件中,需先完成数据库的基本配置。数据库操作必须严格使用 use think\Db; 命名空间进行调用。
数据库配置示例如下:
'db2' => [ 'type' => 'mysql', 'hostname' => '127.0.0.1', 'database' => 'tpshop2', 'username' => 'root', 'password' => '', 'charset' => 'utf8', 'prefix' => 'tp_',],
使用 Db::execute 方法执行插入操作:
$result = Db::execute('insert into sb_ad (ad_name, ad_content ,status) values (1, "456", 1)');// 查看结果dump($result); 使用 Db::execute 方法执行更新操作:
$result = Db::execute('update sb_ad set ad_name = "framework" where ad_id = 1');// 查看结果dump($result); 使用 Db::query 方法执行查询操作:
$result = Db::query('select * from sb_ad where ad_id = 1');// 查看结果print_r($result); 使用 Db::execute 方法执行删除操作:
$result = Db::execute('delete from sb_ad where ad_id = 2');// 查看结果dump($result); $result = Db::query('show tables from tpshop1');// 查看结果print_r($result); $result = Db::execute('TRUNCATE table sb_ad');// 查看结果dump($result); 在 application/config.php 文件中添加多数据库配置,例如:
'db2' => [ 'type' => 'mysql', 'hostname' => '127.0.0.1', 'database' => 'tpshop2', 'username' => 'root', 'password' => '', 'charset' => 'utf8', 'prefix' => 'tp_',],
$result = Db::connect('db2')->query('select * from sb_ad where ad_id = 1');// 查看结果print_r($result); $db1 = Db::connect('db1');$db2 = Db::connect('db2');// 执行查询$resultDb1 = $db1->query('select * from sb_ad where ad_id = 1');$resultDb2 = $db2->query('select * from sb_ad where ad_id = 1'); 使用数组形式传递参数:
$result = Db::execute('insert into sb_ad (ad_name, ad_content ,status) values (?, ?, ?)', [3, 'thinkphp', 1]);// 查看结果dump($result); $result = Db::execute('insert into sb_ad (ad_name, ad_content ,status) values (:ad_name, :ad_content, :status)', [ 'ad_name' => 11, 'ad_content' => 'thinkphp', 'status' => 1]);// 查看结果dump($result); $result = Db::query('select * from sb_ad where ad_id = ?', [3]);// 查看结果print_r($result); 在实际使用中,建议根据数据库类型和连接方式进行适当的优化设置。例如,MySQL数据库默认字符集为utf8,建议统一使用utf8编码。
转载地址:http://vjtfk.baihongyu.com/