1、学习的方法,最好是看手册
在前一篇文章中涉及到了连接数据库sqlsrv_connect()还记得我们mysql连接数据库的时候也是mysql_connect()两者 *** 作数据库是很相似的。从零基础开始学起的话,只能是查阅手册。查看一下sqlsrv有哪些函数提供我们使用!推荐网址是:
【注意】很多的方法都跟mysql提供的方法很相似,看到后面的函数名就大概知道里面的用法,比如说mysql执行sql语句的时候调用mysql_query()而sqlserver执行sql语句的时候调用也是sqlsrv_query(),但是特别注意一点就是,它们的传递参数不一样。详细的只能看一下手册。接下来我简单总结一下 *** 作数据的方法
2、连接数据库sqlsrv_connect()
<?php$serverName = "serverName\sqlexpress"//服务器的名字,本地localhost$connectionInfo = array( "Database"=>"dbName", "UID"=>"userName", "PWD"=>"password")$conn = sqlsrv_connect( $serverName, $connectionInfo)if( $conn ) { echo "Connection established.<br />"
}else{ echo "Connection could not be established.<br />" die( print_r( sqlsrv_errors(), true))
}
3、 *** 作数据库
1)执行sql语句sqlsrv_query(),返回值为true或者false,这里函数的用法跟mysql_query(),不一样。它需要把连接的资源句柄当作参数传进去,看源码。资源句柄就是上面代码连接数据库的“$conn”。
$sql = "select * from test1" //sql语句$data = sqlsrv_query($conn,$sql) //$conn资源句柄if($data == true){ die("执行成功")
}else{ die("执行失败")
}
2)获取结果集
//以数值索引数组、关联数组或这两种数组的形式检索下一行的数据。类似于mysql_fetch_arraysqlsrv_fetch_array
//以对象形式检索下一行的数据。sqlsrv_fetch_object 1234
$sql = "select * from test1"$data = sqlsrv_query($conn,$sql)if($data == true){ while($row = sqlsrv_fetch_array( $data, SQLSRV_FETCH_ASSOC) ) { echo $row['id'].", ".$row['name']."<br />"
}else{ die( print_r( sqlsrv_errors(), true))
}
}
$sql = "SELECT fName, lName FROM Table_1"$stmt = sqlsrv_query( $conn, $sql)if( $stmt === false ) { die( print_r( sqlsrv_errors(), true))
}while( $obj = sqlsrv_fetch_object( $stmt)) { echo $obj->fName.", ".$obj->lName."<br />"
}
3)显示错误信息sqlsrv_errors():上面都有用到这个函数,只要是 *** 作数据库发生错误,都可以使用这个函数打印出来看一下压
这里就不用上代码了
PHP连接数据库之PHP连接MYSQL数据库代码
< ?php $mysql_server_name= localhost //改成自己的mysql数据库服务器 $mysql_username= root //改成自己的mysql数据库用户名 $mysql_password= //改成自己的mysql数据库密码 $mysql_database= mycounter //改成自己的mysql数据库名 $conn=mysql_connect($mysql_server_name $mysql_username $mysql_password $mysql_database) $sql= CREATE DATABASE mycounter DEFAULT CHARACTER SET gbk COLLATE gbk_chinese_ci mysql_query($sql) $sql= CREATE TABLE `counter` (`id` INT( ) UNSIGNED NOT NULL AUTO_INCREMENT `count` INT( ) UNSIGNED NOT NULL DEFAULT PRIMARY KEY ( `id` ) ) TYPE = innodb mysql_select_db($mysql_database $conn) $result=mysql_query($sql) //echo $sql mysql_close($conn) echo "Hello!数据库mycounter已经成功建立!" ?>PHP连接数据库之PHP连接ACCESS数据库代码方法
< ? $conn = new ("ADODB Connection") $connstr = "DRIVER={Microsoft Access Driver (* mdb)} DBQ=" realpath("data/db mdb") $conn >Open($connstr) $rs = new ("ADODB RecordSet") $rs >Open("select * from szd_t" $conn ) while(! $rs >eof) { $f = $rs >Fields( ) echo $f >value $rs >MoveNext() } ?>
PHP连接数据库之PHP连接MS SQL数据库代码方法
安装SQL服务器并添加PHP的MSSQL扩展
使用以下代码连接并测试
< ?php $myServer = localhost //主机 $myUser = sa //用户名 $myPass = password //密码 $myDB = Northwind //MSSQL库名 $s = @mssql_connect($myServer $myUser $myPass) or die(Couldnt connect to SQL Server on $myServer) $d = @mssql_select_db($myDB $s) or die(Couldnt open database $myDB) $query = SELECT TitleOfCourtesy+ +FirstName+ +LastName AS Employee $query = FROM Employees $query = WHERECountry=USA AND Left(HomePhone ) = ( ) $result = mssql_query($query) $numRows = mssql_num_rows($result) echo <h > $numRows Row ($numRows == ? : s) Returned </ h > while($row = mssql_fetch_array($result)) { echo <li> $row[Employee] </li> } ?>
PHP连接数据库之PHP连接Oracle数据库
PHP提供了两套函数与Oracle连接 分别是ORA_和OCI函数 其中ORA_函数略显陈旧 OCI函数更新据说更好一些 两者的使用语法几乎相差无几 你的PHP安装选项应该可以支持两者的使用
< ? if ($conn=Ora_Logon("user@TNSNAME" "password")) { echo "SUCCESS ! Connected to databasen" }else {echo "Failed : ( Could not connect to databasen"} Ora_Logoff($conn) phpinfo() ?> lishixinzhi/Article/program/PHP/201405/30761
本篇文章是对使用PHP执行 SQL文件的实现代码进行了详细的分析介绍 需要的朋友参考下
demo php:
复制代码 代码如下: <?php /** * 读取 sql 文件并写入数据库 * @version demo php */ class DBManager { var $dbHost = var $dbUser = var $dbPassword = var $dbSchema = function __construct($host $user $password $schema) { $this >dbHost = $host $this >dbUser = $user $this >dbPassword = $password $this >dbSchema = $schema } function createFromFile($sqlPath $delimiter = (/n)|((/r/n))|(/r) $prefix = $menter = array( # )) { //判断文件是否存在 if(!file_exists($sqlPath)) return false $handle = fopen($sqlPath rb ) $sqlStr = fread($handle filesize($sqlPath)) //通过sql语法的语句分割符进行分割 $segment = explode("" trim($sqlStr)) //var_dump($segment) //去掉注释和多余的空行 foreach($segment as &$statement) { $sentence = explode("/n" $statement) $newStatement = array() foreach($sentence as $subSentence) { if( != trim($subSentence)) { //判断是会否是注释 $isComment = false foreach($menter as $er) { if(eregi("^(" $er ")" trim($subSentence))) { $isComment = true break } } //如果不是注释 则认为是sql语句 if(!$isComment) $newStatement[] = $subSentence } } $statement = $newStatement } //对表名加前缀 if( != $prefix) { //只有表名在第一行出现时才有效 例如 CREATE TABLE talbeName $regxTable = "^[/`/ /"]{ }[/_a zA Z]+[/_a zA Z ]*[/`/ /"]{ }$"//处理表名的正则表达式 $regxLeftWall = "^[/`/ /"]{ }" $sqlFlagTree = array( "CREATE" =>array( "TABLE" =>array( "$regxTable" => ) ) "INSERT" =>array( "INTO" =>array( "$regxTable" => ) ) ) foreach($segment as &$statement) { $tokens = split(" " $statement[ ]) $tableName = array() $this >findTableName($sqlFlagTree $tokens $tableName) if(empty($tableName[ leftWall ])) { $newTableName = $prefix $tableName[ name ] } else{ $newTableName = $tableName[ leftWall ] $prefix substr($tableName[ name ] ) } $statement[ ] = str_replace($tableName[ name ] $newTableName $statement[ ]) } } //组合sql语句 foreach($segment as &$statement) { $newStmt = foreach($statement as $sentence) { $newStmt = $newStmt trim($sentence) "/n" } $statement = $newStmt } //用于测试 //var_dump($segment) //writeArrayToFile( data txt $segment) // self::saveByQuery($segment) return true } private function saveByQuery($sqlArray) { $conn = mysql_connect($this >dbHost $this >dbUser $this >dbPassword) mysql_select_db($this >dbSchema) foreach($sqlArray as $sql) { mysql_query($sql) } mysql_close($conn) } private function findTableName($sqlFlagTree $tokens $tokensKey= &$tableName = array()) { $regxLeftWall = "^[/`/ /"]{ }" if(count($tokens)<=$tokensKey) return false if( == trim($tokens[$tokensKey])) { return self::findTableName($sqlFlagTree $tokens $tokensKey+ $tableName) } else { foreach($sqlFlagTree as $flag =>$v) { if(eregi($flag $tokens[$tokensKey])) { if( ==$v) { $tableName[ name ] = $tokens[$tokensKey] if(eregi($regxLeftWall $tableName[ name ])) { $tableName[ leftWall ] = $tableName[ name ]{ } } return true } else{ return self::findTableName($v $tokens $tokensKey+ &$tableName) } } } } return false } } function writeArrayToFile($fileName $dataArray $delimiter="/r/n") { $handle=fopen($fileName "wb") $text = foreach($dataArray as $data) { $text = $text $data $delimiter } fwrite($handle $text)} //测试 $dbM = new DBManager( localhost w f test )$dbM >createFromFile( data sql null fff_ )?>lishixinzhi/Article/program/PHP/201311/21281
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)