Thinkphp5结合Adodb连接access数据库
解决问题:
1.安装adodb:composer require adodb/adodb-php
;
2.adodb连接数据库 Base.php:
class Base
{
var $dbtype; //定义成员变量,数据库类型
var $host; //定义成员变量,数据库服务器
var $user; //定义成员变量,服务器用户名
var $pwd; //定义成员变量,服务器密码
var $dbname; //定义数据库名称
var $debug; //定义返回错误信息
var $conn; //定义返回的连接标识
var $coded; //数据库的编码格式
var $adodb;
public function __construct()
{
$this->dbtype = Datebase::dbtype;
$this->host = Datebase::host;
$this->user = Datebase::user;
$this->pwd = Datebase::pwd;
$this->dbname = Datebase::dbname;
$this->debug = Datebase::debug;
$this->coded = Datebase::coded;
if (empty($this->conn)) {
$conn = $this->GetConnId();
if ($conn->_errorMsg) {
echo "数据库连接失败,".$conn->_errorMsg;
die;
}
}
}
//获取数据库连接ID
//composer require adodb/adodb-php
public function GetConnId()
{
if ($this->dbtype == "mysql" || $this->dbtype == "mssql") { //判断成员变量传递的数据库类型
if ($this->dbtype == "mysql") //判断如果是MySQL数据库
$this->conn = NewADOConnection("mysql"); //执行与MySQl数据库的连接
else
$this->conn = NewADOConnection("mssql");
$this->conn->Connect($this->host, $this->user, $this->pwd, $this->dbname); //数据库连接的用户、密码
} elseif ($this->dbtype == "access") { //判断如果使用的是Access数据库
$this->conn = NewADOConnection("access");
$this->conn->Connect("Driver={Microsoft Access Driver (*.mdb)};Dbq=" . $this->dbname . ";Uid=" . $this->user . ";Pwd=" . $this->pwd . ";"); //执行连接Access数据库
} elseif ($this->dbtype == 'ado_access') {
$this->conn = NewADOConnection("ado_access");
$this->conn->Connect('PROVIDER=Microsoft.Jet.OLEDB.4.0;' . 'DATA SOURCE=' . realpath($this->dbname) . ';' . "Jet OLEDB:Database Password=" . $this->pwd . ';');
}
$this->conn->SetFetchMode(ADODB_FETCH_ASSOC); //设置读取数据的模式
$this->conn->Execute($this->coded); //设置数据库的编码格式
if ($this->dbtype == "mysql")
$this->conn->debug = $this->debug;
return $this->conn; //返回连接对象
}
//定义关闭数据库的方法
public function CloseConnId()
{
@$this->conn->Disconnect(); //执行关闭的操作
}
}
3.CURD Admin.php操作类(需继承Base.php)
class Admin extends Base
{
//执行SQL
public function executeSQL($sql)
{
$connID = $this->conn;
$sqlType = strtolower(substr(trim($sql), 0, 6)); //提取SQL语句的类型
$rs = $connID->Execute($sql); //执行SQL语句
if ($sqlType == 'select') { //如果是select查询
$arrayData = $rs->GetRows(); //返回查询记录集
if (count($arrayData) == 0 || $rs == false) { //如果没查询到或发生错误
return false; //返回false
} else { //否则
return $arrayData; //返回记录集
}
} elseif ($sqlType == 'insert' || $sqlType == 'update' || $sqlType == 'delete') { //如果执行插入、更新或删除语句
return $rs; //返回语句执行状态,即成功返回true,失败返回false
} else {
return false; //如果不是上述查询,则返回false
}
}
4.处理输出数据编码问题:
//utf8 gbk 数组 互转
protected function array_iconv($arr, $in_charset = "gbk", $out_charset = "utf-8")
{
$ret = eval('return ' . iconv($in_charset, $out_charset, var_export($arr, true) . ';'));
return $ret;
}
5.可以通过TP生成SQL语句,调用Admin使用
$where=[];
$sql=(new AdminModel())->where($where)->select(false);
$list=(new Admin())->executeSQL($sql);