天天看點

Discuz!X/多資料庫配置與使用方法

如果負載足夠搞,是可以把很一些表分布在多台資料庫伺服器中。這樣來減小負載

可以友善的使用别的資料庫中的資料。

在/config/config_global.php 檔案中增加資料表和伺服器之間的映射關系,還有相應資料庫伺服器配置。加入以下代碼

Discuz!X/多資料庫配置與使用方法

 //2的意思是随後配置的資料庫連接配接參數  

$_config['db']['map']=array('表名'=>'2');  

//這裡面2對應映射配置  

$_config['db']['2']['dbhost'] = 'localhost';  

$_config['db']['2']['dbuser'] = 'root';  

$_config['db']['2']['dbpw'] = '';  

$_config['db']['2']['dbcharset'] = 'gbk';  

$_config['db']['2']['pconnect'] = '0';  

$_config['db']['2']['dbname'] = '資料庫名';  

//這個參數其實沒有用,要照我随後的修改就可以用了  

$_config['db']['2']['tablepre'] = 'cdb_';  

在程式中使用就很友善了。直接使用db靜态對象

Discuz!X/多資料庫配置與使用方法

print_r(db::fetch_first("select * from ".db::table('表名')." limit 1"));   

一定要使用db::table方法,因為通過這個方法來轉換資料庫連接配接。

一些聯表查詢不能使用

外聯資料庫的表字首一定得和現在的表字首一樣。如 pre_表名

如果需要使用其它資料庫的非discuz的表,可以修改 class_core 的 table_name 函數,這樣就不用限制 pre_ 表字首了。而且配置中的資料庫字首也可以用了。

Discuz!X/多資料庫配置與使用方法

function table_name($tablename) {  

    if(!empty($this->map) && !empty($this->map[$tablename])) {  

        $id = $this->map[$tablename];  

        if(!$this->link[$id]) {  

            $this->connect($id);  

        }  

        $this->curlink = $this->link[$id];  

        //增加了這一句  

        return $this->config[$id]['tablepre'].$tablename;  

    } else {  

        $this->curlink = $this->link[1];  

    }  

    return $this->tablepre.$tablename;  

}