以下代码将数据集作为一个数组返回,再搜索数组中有没有你需要的列。
因为是自己平时用的,看起来很长,其实在 92 行的循环中可以加判断有没有存在你要的 列名。不生成数组也可以。
#include <Array.au3>
$Server = ""
$Username = ""
$Password = ""
$Database = ""
$Obj = _MsSQL_Connect($Server, $Username, $Password, $Database)
If Not @error Then
$ARRAY = _MsSQL_SelectTable($Obj, "sys.columns", "name", "object_id=object_id(' ')")
If Not @error Then
_ArrayDisplay($ARRAY)
Else
EndIf
EndIf
Func _MsSQL_Connect($sServer, $sUsername, $sPassword, $sDatabase, $Auth = True, $sPort=1433, $sDriver = "{SQL Server}")
If $sServer = "" Or $sUsername = "" Or $sPassword = "" Or $sDatabase = "" Then
SetError(1)
Return
EndIf
Local $v = StringMid($sDriver, 2, StringLen($sDriver) - 2)
Local $val = RegRead("HKEY_LOCAL_MACHINE\SOFTWARE\ODBC\ODBCINST.INI\ODBC Drivers", $v) ;检查OBDC驱动是否安装
If @error Or $val = "" Then
SetError(3)
Return
EndIf
$conn = ObjCreate("ADODB.Connection")
If Not IsObj($conn) Then
SetError(4)
Return
EndIf
If $sPort = "" Then $sPort = 1433
If $sPort = 1433 Then
$Port = ''
Else
$Port = ',' & $sPort
EndIf
If $Auth = True Then
ConsoleWrite("driver={SQL Server};server="&$sServer&$Port&";uid="&$sUsername&";pwd="&$sPassword&";database="&$sDatabase & @CRLF)
$conn.Open("driver={SQL Server};server="&$sServer&$Port&";uid="&$sUsername&";pwd="&$sPassword&";database="&$sDatabase) ;主机名IP127.0.0.1,UID=用户,PWD=密码,database=数据库名 ?
Else
ConsoleWrite("driver={SQL Server};server="&$sServer&$Port&";uid="&$sUsername&";pwd="&$sPassword&";database="&$sDatabase&";Integrated Security=SSPI" & @CRLF)
$conn.Properties.Value("Integrated Security") = "SSPI"
$conn.Properties("uid") = $sUsername
$conn.Properties("pwd") = $sPassword
$conn.Open("driver={SQL Server};server=" & $sServer & ";database="&$sDatabase)
EndIf
If @error Then
SetError(5)
Return
Else
Return $conn
EndIf
EndFunc
Func _MsSQL_SelectTable($Obj, $Table, $Field = '*', $Condition = '', $Distinct = 0, $OrderByCMD = "") ;表查询,Condition = WHERE, Distinct <> 0 将去掉重复项,只返回不重复的值
If Not IsObj($Obj) Then
SetError(1)
Return
ElseIf $Table = "" Then
SetError(2)
Return
EndIf
$RS = ObjCreate("ADODB.Recordset")
$RS.ActiveConnection = $Obj
Local $WHERE = "", $DIS = "", $OrderBy = ""
If $Condition <> "" Then $WHERE = " WHERE " & $Condition
If $OrderByCMD <> "" Then $OrderBy = " ORDER BY " & $OrderByCMD
If $Distinct = 1 Then $DIS = "DISTINCT " ;排除重复项
ConsoleWrite("SELECT " & $DIS & $Field & " FROM " & $Table & $WHERE & $OrderBy & @CRLF)
$RS.Open("SELECT " & $DIS & $Field & " FROM " & $Table & $WHERE & $OrderBy)
Local $FieldNum = $RS.Fields.Count
If $FieldNum = 1 Then
$FieldNum2 = 2 ;虽然数据只有1列,但数组是二唯的,容量发生混乱,干脆生成二唯数组
Else
$FieldNum2 = $FieldNum
EndIf
Local $Num = 0, $Array[1][$FieldNum2] = [[0]], $text = ""
While Not $RS.eof And Not $RS.bof
For $i = 0 To $FieldNum-1 ;循环读取字段值
$Text &= $RS.Fields($i).value & "|"
Next
_ArrayAdd($Array, StringTrimRight($Text, 1)) ;通常会多加一个|,会导致数组维数不对
$text = ""
$Num += 1
$RS.movenext;下一笔资料
WEnd
$RS.close
If $Num = 0 Then
SetError(5)
Return
Else
$Array[0][0] = $Num
Return $Array
EndIf
EndFunc
|