protected $connection = [
// 数据库类型
'type' => 'mysql',
// 数据库连接DSN配置
'dsn' => '',
// 服务器地址
'hostname' => '127.0.0.1',
// 数据库名
'database' => 'test',
// 数据库用户名
'username' => 'root',
// 数据库密码
'password' => 'root',
// 数据库连接端口
'hostport' => '',
// 数据库连接参数
'params' => [],
// 数据库编码默认采用utf8
'charset' => 'utf8',
// 数据库表前缀
'prefix' => 'acc_dragon_',
];
/**
* 清空数据库表
*
* @param string $tblname 表名
* @return void
*/
public function truncateTable($tblname)
{
try {
$sql = "TRUNCATE TABLE " . $tblname;
$Db = Db::connect($this->connection); //修改数据库连接
Db::execute($sql); //执行清空表操作
} catch (\Exception $e) {
throw new \think\Exception($e->getMessage());
}
}为了调试方便临时把数据库连接动态配置为本地数据库(默认使用的是远程阿里云数据库),但是执行完发现,被清空的竟然还是远程的数据库。问题是我动态修改完之后我看到Db的连接已经被修改为本地连接了:
$Db = Db::connect($this->connection); //修改数据库连接
dump($Db);
以下执行结果:
object(think\db\connector\Mysql)#13 (15) {
["builder":protected] => string(23) "\think\db\builder\Mysql"
["PDOStatement":protected] => NULL
["queryStr":protected] => string(0) ""
["numRows":protected] => int(0)
["transTimes":protected] => int(0)
["error":protected] => string(0) ""
["links":protected] => array(0) {
}
["linkID":protected] => NULL
["linkRead":protected] => NULL
["linkWrite":protected] => NULL
["fetchType":protected] => int(2)
["attrCase":protected] => int(2)
["config":protected] => array(24) {
["type"] => string(5) "mysql"
["hostname"] => string(9) "127.0.0.1"
["database"] => string(4) "test"
["username"] => string(4) "root"
["password"] => string(4) "root"
["hostport"] => string(0) ""
["dsn"] => string(0) ""
["params"] => array(0) {
}
["charset"] => string(4) "utf8"
["prefix"] => string(11) "acc_dragon_"
["debug"] => bool(false)
["deploy"] => int(0)
["rw_separate"] => bool(false)
["master_num"] => int(1)
["slave_no"] => string(0) ""
["fields_strict"] => bool(true)
["result_type"] => int(2)
["resultset_type"] => string(5) "array"
["auto_timestamp"] => bool(false)
["datetime_format"] => string(11) "Y-m-d H:i:s"
["sql_explain"] => bool(false)
["builder"] => string(0) ""
["query"] => string(15) "\think\db\Query"
["break_reconnect"] => bool(false)
}
["params":protected] => array(5) {
[8] => int(0)
[3] => int(2)
[11] => int(0)
[17] => bool(false)
[20] => bool(false)
}
["bind":protected] => array(0) {
}
} 最佳答案