热门标签 | HotTags
当前位置:  开发笔记 > 后端 > 正文

mssql+php数据库操作类

mssql+操作类classDbQueryForMssql{ ** *select方法返回的最大记录数 * constMAX_ROW_NUM100000; ** *数据查询结果集对象 *@varobject$dataSet * p
mssql+操作类

class DbQueryForMssql {
/**
* select方法返回的最大记录数
*/
const MAX_ROW_NUM = 100000;

/**
* 数据查询结果集对象
* @var object $dataSet
*/
public $dataSet = NULL ;

/**
* 数据源对象
* @var object $ds
*/
public $ds = NULL ;

/**
* 查询的SQL语句
* @var string $sql
*/
public $sql = '' ;

public $transCnt = 0;

/**
* 执行查询的模式,值为 OCI_COMMIT_ON_SUCCESS 或 OCI_DEFAULT
* @var string $excuteMode
*/
public $executeMode = OCI_COMMIT_ON_SUCCESS ;

/**
* 构造函数
* @param object $ds 数据库
* @param string $sql 要初始化查询的SQL语句
*/
function __construct($ds=NULL , $sql=NULL) {
if (!$ds) {
$this->error(DbException::DB_UNCONNECTED, '数据库还

未连接。');
} else {
$this->ds = $ds;
if ($sql) {
$this->open($sql);
}
}
}

/**
* 释放所占用的内存
* @param object $dataSet 需要释放资源的结果集
* @access public
*/
public function close($dataSet=NULL) {
if ($dataSet) {
@mssql_free_statement($dataSet);
} else {
@mssql_free_statement($this->dataSet);
$this->eof = false ;
$this->recordCount = 0 ;
$this->recNo = -1 ;
}
}
function __destruct()
{
@mssql_free_result($this->dataSet);
@mssql_free_statement($this->dataSet);
@mssql_close($this->ds->connect);
}
/**
* 对$pass进行数据库加密,返回加密之后的值
* @param string $pass 要加密的字符串
* @return string
* @access public
*/
public function encodePassword($pass) {
return md5($pass);
}

/**
* 得到错误信息和错误代号
* @param integer $queryResult 查询结果
* @return array
* @access protected
*/
protected function errorInfo($queryResult = NULL) {
$result['message'] = mssql_get_last_message();
@mssql_select_db($this->ds->name,$this->ds->connect);
/*if (_select_db($this->ds->name">!@mysql_select_db($this->ds->name)) {
throw new DbException('数据库不存在',

DbException::DB_OPEN_FAILED);
}*/
$id = @mssql_query("select @@ERROR", $this->ds->connect);
if (!$id) {
return false;
}
$arr = mssql_fetch_array($id);
@mssql_free_result($id);
if (is_array($arr)) {
$result['code'] = $arr[0];
} else {
return $result['code'] = -1;
}
return $result;
}

/**
* 错误信息处理
* @param string $errorId 错误ID
* @param string $errorMessage 错误信息
* @access protected
*/
protected function error($errorId, $errorMessage) {
throw new DbException($errorMessage, $errorId);
}

/**
* 执行SQL语句
* @param string $sql SQL语句
* @return object
* @param int $rowFrom 启始行号,行号从1开始
* @param int $rowTo 结束行号,值为0表示
* @access public
* @see DbQuery::open
*/
public function execute($sql = '', $rowFrom = 0, $rowTo =

self::MAX_ROW_NUM, $error = true) {
//echo $this->ds->name;
if ($rowTo != self::MAX_ROW_NUM) {
$nrows = $rowTo - $rowFrom + 1;
}
$offset = $rowFrom;
if ($nrows > 0) {
$nn = $nrows + $offset - 1;
$sql = preg_replace('/(^s*selects+

(distinctrow|distinct)?)/i', '\1 top ' . $nn . ' ', $sql);
}

@mssql_select_db($this->ds->name,$this->ds->connect);
/*if ()) {
throw new DbException('数据库不存在',

DbException::DB_OPEN_FAILED);
}*/
$dataSet = @mssql_query($sql, $this->ds->connect);
//echo $sql .'



';
if (!$dataSet && $error) {
$sqlError = $this->errorInfo();
$errorMessage = '执行[' .

$sql
. '
]出错!

color=#FF0000> ['
. $sqlError['code'] . ']: '
. $sqlError['message'] . '' ;
$this->error(DbException::DB_QUERY_ERROR,

$errorMessage);
}

if ($offset) {
$offset = $offset-1;//var_dump($dataSet);echo 'abc';
$resultNum = mssql_num_rows($dataSet);
if ($resultNum<$offset) {
@mssql_data_seek($dataSet, $resultNum-1);
} else {
@mssql_data_seek($dataSet, $offset);
}
}
return $dataSet;
}

/**
* 执行SQL语句,结果集保存到属性$dataSet中
* @param string $sql SQL语句
* @param int $rowFrom 启始行号,行号从1开始
* @param int $rowTo 结束行号,值为0表示
* @return object
* @access public
* @see DbQuery::execute
*/
public function open($sql='', $rowFrom = 0, $rowTo =

self::MAX_ROW_NUM) {
$this->dataSet = $this->execute($sql, $rowFrom, $rowTo);
$this->sql = $sql ;
return $this->dataSet;
}

/**
* 将一行的各字段值拆分到一个数组中
* @param object $dataSet 结果集
* @param integer $resultType 返回类型,OCI_ASSOC、OCI_NUM 或

OCI_BOTH
* @return array
*/
public function fetchRecord($dataSet=NULL, $resultType=MSSQL_BOTH) {
$result = @mssql_fetch_array(($dataSet) ? $dataSet : $this-

>dataSet, $resultType);
if (is_array($result)) {
foreach ($result as $key => $value) {
if (!is_numeric($key)) {
$result[strtolower($key)] = $value;
}
}
}
return $result;
}

/**
* 取得字段数量
* @param object $dataSet 结果集
* @return integer
*/
public function getFieldCount($dataSet = NULL) {

return mssql_num_fields(($dataSet) ? $dataSet : $this-

>dataSet);
}

/**
* 取得下一条记录。返回记录号,如果到了记录尾,则返回FALSE
* @return integer
* @access public
* @see getPrior()
*/
public function next() {
return $this->fetchRecord();
}

/**
* 得到当前数据库时间,格式为:yyyy-mm-dd hh:mm:ss
* @return string
* @access public
*/
public function getNow() {
return $this->getValue('SELECT TO_CHAR(SYSDATE, 'YYYY-MM-DD

HH24:MI:SS') dateOfNow FROM DUAL');
}

/**
* 根据SQL语句从数据表中取数据,只取第一条记录的值,
* 如果记录中只有一个字段,则只返回字段值。
* 未找到返回 FALSE
*
* @param string $sql SQL语句
* @return array
* @access public
*/
public function getValue($sql = '',$dataFormat=MSSQL_BOTH) {
$dataSet = $this->execute($sql, 1, 1);

if ($result = $this->fetchRecord($dataSet,$dataFormat)) {
$fieldCount = $this->getFieldCount($dataSet);
$idx = 0;
if($dataFormat == MSSQL_ASSOC){//如果使用

MSSQL_ASSOC,且只有一列时,则需要知道第一列的列名.
$firstColumnInfo = mssql_fetch_field

($dataSet ,0 );
$idx = $firstColumnInfo->name;//column name
}
$this->close($dataSet);//print_r($result);
return ($fieldCount<=1) ? $result[$idx] : $result;
} else {
return false ;
}
}

/**
* 取ID自递增值
*
* @return int
* @access public
*/
public function getInsertId() {
return $this->getValue('select @@identity');
}

/**
* 取序列
* @param $seq 序列名
* @return int
* @access public
*/
public function getSeq($seq = '') {
$this->execute('BEGIN TRANSACTION adodbseq');
$ok = $this->execute("update $seq with (tablock,holdlock)

set id = id + 1", 0, self::MAX_ROW_NUM, false);
if (!$ok) {
$this->execute("create table $seq (id float(53))");
$ok = $this->execute("insert into $seq with

(tablock,holdlock) values(1)", 0, self::MAX_ROW_NUM, false);
if (!$ok) {
$this->execute('ROLLBACK TRANSACTION

adodbseq');
return false;
}
$this->execute('COMMIT TRANSACTION adodbseq');
return 1;
}
$num = $this->getValue("select id from $seq");
$this->execute('COMMIT TRANSACTION adodbseq');
return $num;
}
/**
* 表是否存在,返回true
* @param string $tableName 要查询的表名
* @return bool
* @access public
*/
public function tableIsExists($tableName) {
return false;
}

/**
* 开始事务
* @access public
*/
public function begin() {
$this->transCnt += 1;
$this->execute('BEGIN TRAN');
return true;
}

/**
* 提交事务
* @access public
*/
public function commit() {
if ($this->transCnt) {
$this->transCnt -= 1;
}
$this->execute('COMMIT TRAN');
return true;
}

/**
* 回滚事务
* @access public
*/
public function rollback() {
if ($this->transCnt){
$this->transCnt -= 1;
}
$this->execute('ROLLBACK TRAN');
return true;
}

/**
* 插入一条记录
* @param string $tableName 表名
* @param array $fieldArray 字段数组
* @param string $whereForUnique 唯一性条件
* @return int
* @access public
*/
public function insert($tableName, $fieldArray, $whereForUnique =

NULL) {
if (!$tableName || !$fieldArray || !is_array($fieldArray)) {
throw new Exception('参数 $tableName 或 $fieldArray

的值不合法!');
}
if ($whereForUnique) {
$where = ' WHERE ' . $whereForUnique;
$isExisted = $this->getValue('SELECT COUNT(*) FROM '

. $tableName . $where);
if ($isExisted) {
throw new DbException('记录已经存在!',

DbException::DB_RECORD_IS_EXISTED);
}
}
$fieldNameList = array();
$fieldValueList = array();
foreach ($fieldArray as $fieldName => $fieldValue) {
if (!is_int($fieldName)) {
$fieldNameList[] = $fieldName;
$fieldValueList[] = ''' . $fieldValue .

''';
}
}
$fieldName = implode(',', $fieldNameList);
$fieldValue = implode(',', $fieldValueList);
$sql = 'INSERT INTO ' . $tableName . '('
. $fieldName . ') VALUES (' .

$fieldValue . ')';
//return $sql;
return $this->execute($sql);
}

/**
* 更新一条记录
* @param string $tableName 表名
* @param array $fieldArray 字段数组
* @param string $whereForUpdate 查询条件
* @param string $whereForUnique 唯一性条件
* @return int
* @access public
*/
public function update($tableName, $fieldArray,

$whereForUpdate=NULL, $whereForUnique=NULL) {
if (!$tableName || !$fieldArray || !is_array($fieldArray)) {
throw new Exception('参数 $tableName 或 $fieldArray

的值不合法!');
}
if ($whereForUnique) {
$where = ' WHERE ' . $whereForUnique;
$isExisted = $this->getValue('SELECT COUNT(*) FROM '

. $tableName . $where);
if ($isExisted) {
throw new DbException('记录已经存在!',

DbException::DB_RECORD_IS_EXISTED);
}
}
$fieldNameValueList = array();
foreach ($fieldArray as $fieldName => $fieldValue) {
if (!is_int($fieldName)) {
$fieldNameValueList[] = $fieldName . '='' .

$fieldValue . ''';
}
}
$fieldNameValue = implode(',', $fieldNameValueList);
if ($whereForUpdate) {
$whereForUpdate = ' WHERE ' . $whereForUpdate;
}
$sql = 'UPDATE ' . $tableName
. ' SET ' . $fieldNameValue .

$whereForUpdate;
return $this->execute($sql);
//return $sql;
}

/**
* 选择一条记录
* @param string $sql sql语句
* @param string $dataFormat 返回数据格式, 值

有"array","hashmap","hashmap_str","dataset"
* @param int $rowFrom 启始行号,行号从1开始
* @param int $rowTo 结束行号,值为0表示
* @result array
* @access public
*/
public function select($sql, $dataFormat = 'array', $rowFrom = 0,

$rowTo = self::MAX_ROW_NUM) {
$dataSet = $this->execute($sql, $rowFrom, $rowTo);
switch ($dataFormat) {
case 'array': //数组
$result = array();
$isMultiField = ($this->getFieldCount($dataSet) >

1);
$i = 0;
while ($data = $this->fetchRecord($dataSet)) {
$result[$i] = ($isMultiField) ? $data :

$data[0];
$i++;
}
$this->close($dataSet);
break;

case 'arrayassoc': //数组,有BUG,这里面需要用列名为索引!当只

有一列有时候
$result = array();
$isMultiField = ($this->getFieldCount($dataSet) >

1);
$i = 0;
while ($data = $this->fetchRecord

($dataSet,MSSQL_ASSOC)) {
$idx = 0;
if(!$isMultiField){//只有一列的话
if($dataFormat == MSSQL_ASSOC){//用

MSSQL_ASSOC,且只有一列时,则需要知道第一列的列名.
$firstColumnInfo = mssql_fetch_field

($dataSet ,0 );
$idx = $firstColumnInfo-

>name;//column name
}
}
$result[$i] = ($isMultiField) ? $data :

$data[$idx];
$i++;
}
$this->close($dataSet);
break;

case 'hashmap': //散列表
$result = array();
while ($data = $this->fetchRecord($dataSet)) {
$result[ $data[0] ] = $data[1];
}
$this->close($dataSet);
break;

case 'hashmap_str': //散列表字符串
$result = array();
while ($data = $this->fetchRecord($dataSet,

OCI_NUM)) {
$result[] = $data[0] . '=' . $data[1];
}
$result = implode('|', $result);
$this->close($dataSet);
break;

default: //dataset 数据集,当返回数据格式为数据集时,select

方法的功能与execute方法相同
$result = $dataSet;
}
return $result;
}

/**
* 返回最大值
* @param string $tableName 表名
* @param string $idField 字段名
* @param string $where 查询条件
* @return int
* @access public
*/
public function getMax($tableName, $idField, $where = NULL) {
$where = ($where) ? (' WHERE ' . $where) : '';
return $this->getValue('SELECT MAX(' . $idField . ') FROM '

. $tableName . $where);
}
}

推荐阅读
  • 本文介绍了如何在MySQL中将零值替换为先前的非零值的方法,包括使用内联查询和更新查询。同时还提供了选择正确值的方法。 ... [详细]
  • 在数据分析工作中,我们通常会遇到这样的问题,一个业务部门由若干业务组构成,需要筛选出每个业务组里业绩前N名的业务员。这其实是一个分组排序的 ... [详细]
  • 本文介绍了如何使用php限制数据库插入的条数并显示每次插入数据库之间的数据数目,以及避免重复提交的方法。同时还介绍了如何限制某一个数据库用户的并发连接数,以及设置数据库的连接数和连接超时时间的方法。最后提供了一些关于浏览器在线用户数和数据库连接数量比例的参考值。 ... [详细]
  • Oracle Database 10g许可授予信息及高级功能详解
    本文介绍了Oracle Database 10g许可授予信息及其中的高级功能,包括数据库优化数据包、SQL访问指导、SQL优化指导、SQL优化集和重组对象。同时提供了详细说明,指导用户在Oracle Database 10g中如何使用这些功能。 ... [详细]
  • 在说Hibernate映射前,我们先来了解下对象关系映射ORM。ORM的实现思想就是将关系数据库中表的数据映射成对象,以对象的形式展现。这样开发人员就可以把对数据库的操作转化为对 ... [详细]
  • 本文详细介绍了MysqlDump和mysqldump进行全库备份的相关知识,包括备份命令的使用方法、my.cnf配置文件的设置、binlog日志的位置指定、增量恢复的方式以及适用于innodb引擎和myisam引擎的备份方法。对于需要进行数据库备份的用户来说,本文提供了一些有价值的参考内容。 ... [详细]
  • 本文由编程笔记小编整理,介绍了PHP中的MySQL函数库及其常用函数,包括mysql_connect、mysql_error、mysql_select_db、mysql_query、mysql_affected_row、mysql_close等。希望对读者有一定的参考价值。 ... [详细]
  • Spring特性实现接口多类的动态调用详解
    本文详细介绍了如何使用Spring特性实现接口多类的动态调用。通过对Spring IoC容器的基础类BeanFactory和ApplicationContext的介绍,以及getBeansOfType方法的应用,解决了在实际工作中遇到的接口及多个实现类的问题。同时,文章还提到了SPI使用的不便之处,并介绍了借助ApplicationContext实现需求的方法。阅读本文,你将了解到Spring特性的实现原理和实际应用方式。 ... [详细]
  • PHP设置MySQL字符集的方法及使用mysqli_set_charset函数
    本文介绍了PHP设置MySQL字符集的方法,详细介绍了使用mysqli_set_charset函数来规定与数据库服务器进行数据传送时要使用的字符集。通过示例代码演示了如何设置默认客户端字符集。 ... [详细]
  • 本文介绍了Redis的基础数据结构string的应用场景,并以面试的形式进行问答讲解,帮助读者更好地理解和应用Redis。同时,描述了一位面试者的心理状态和面试官的行为。 ... [详细]
  • 本文介绍了在Hibernate配置lazy=false时无法加载数据的问题,通过采用OpenSessionInView模式和修改数据库服务器版本解决了该问题。详细描述了问题的出现和解决过程,包括运行环境和数据库的配置信息。 ... [详细]
  • 原文地址:https:www.cnblogs.combaoyipSpringBoot_YML.html1.在springboot中,有两种配置文件,一种 ... [详细]
  • Metasploit攻击渗透实践
    本文介绍了Metasploit攻击渗透实践的内容和要求,包括主动攻击、针对浏览器和客户端的攻击,以及成功应用辅助模块的实践过程。其中涉及使用Hydra在不知道密码的情况下攻击metsploit2靶机获取密码,以及攻击浏览器中的tomcat服务的具体步骤。同时还讲解了爆破密码的方法和设置攻击目标主机的相关参数。 ... [详细]
  • 本文介绍了在SpringBoot中集成thymeleaf前端模版的配置步骤,包括在application.properties配置文件中添加thymeleaf的配置信息,引入thymeleaf的jar包,以及创建PageController并添加index方法。 ... [详细]
  • 使用Ubuntu中的Python获取浏览器历史记录原文: ... [详细]
author-avatar
vbppn65853
这个家伙很懒,什么也没留下!
PHP1.CN | 中国最专业的PHP中文社区 | DevBox开发工具箱 | json解析格式化 |PHP资讯 | PHP教程 | 数据库技术 | 服务器技术 | 前端开发技术 | PHP框架 | 开发工具 | 在线工具
Copyright © 1998 - 2020 PHP1.CN. All Rights Reserved | 京公网安备 11010802041100号 | 京ICP备19059560号-4 | PHP1.CN 第一PHP社区 版权所有