Thinkai's Blog

Autohotkey|Python|php|aardio|VOIP|IT 爱好者

ffmpeg静音检测 Autohotkey 3076

作者为 发表

Autohotkey

;使用方法
s := silenceDetect("test.wav",30) ;检测test.wav中响度低于-30db的静音区
;返回数组,单个值包含键值:start开始时间,end结束时间, duration:时长

silenceDetect(file,db := 40){
	out_file := A_ScriptDir "\tmp\" GUID() ".wav" ;注意脚本目录下要有tmp文件夹
	ret := cmd("""" A_ScriptDir "\tools\ffmpeg64.exe"" -i """ file """ -af silencedetect=n=-" db "dB:d=1 -y """ out_file """","UTF-8")
	s := []
	l := StrSplit(ret,"`r","`n")
	for k,v in l
	{
		if RegExMatch(v,"\[silencedetect[^\]]*\]\ssilence_start:\s([0-9\.]*)",m)
			s.push({"start":floor(m1*1000)})
		else if RegExMatch(v,"\[silencedetect[^\]]*\]\ssilence_end:\s([0-9\.]*)\s\|\ssilence_duration:\s([0-9\.]*)",m)
			s[s.maxindex()].end := floor(m1*1000), s[s.maxindex()].duration := floor(m2*1000)
	}
	FileDelete % out_file
	return s
}

GUID(){
	shellobj := ComObjCreate("Scriptlet.TypeLib")
	ret := shellobj.GUID
	uuid := RegExReplace(ret,"(\{|\}|-)","")
	return uuid
}


info := audioinfo("test.mp3")
msgbox, 64, Notice, % "The File duration is " info.duration "!"

audioinfo(file){
	ret := cmd(A_ScriptDir "\tools\ffmpeg64.exe -i """ file """") ;32位请去掉64
	if RegExMatch(ret, "Audio:\s*([^\s]+)\s*\(*[^\)]*\)*,\s*(\d+)\s*Hz,\s*([^,]+),\s*([^,]+),\s*([^,]+)\skb/s", match)
	{
		RegExMatch(ret,"Duration:(\s*[^,]+),",dur)
		return {"code":match1,"samRate":match2,"tract":match3,"dep":match4,"bitRate":match5,"duration":dur1}
	}
}


毫秒 时间字符串互转 Autohotkey 1694

作者为 发表

Autohotkey

time2msc(time){ ;e.g. 01:01:22.342
	a := StrSplit(time,".")
	b := StrSplit(a.1,":")
	f := "0." a.2
	return floor(b.1*1000*60*60+b.2*1000*60+b.3*1000+f*1000)
}

msc2time(msc){
	return Format("{1:02d}", floor(msc/1000/60/60)) ":" Format("{1:02d}", Mod(floor(msc/1000/60),60)) ":" Format("{1:02d}", Mod(floor(msc/1000),60)) "." Format("{1:03d}", Mod(msc,1000))
}


开机自动设置电脑IP Autohotkey 1575

作者为 发表

Autohotkey

功能:开机自动设置活动网卡的IP等信息,并保存配置到同目录ini文件。

;--------------------------开机启动------------------
RegRead, var, HKCU, Software\Microsoft\Windows\CurrentVersion\Run, SetIP
last := A_LastError
if last=2
	RegWrite, REG_SZ, HKCU, Software\Microsoft\Windows\CurrentVersion\Run, SetIP, "%A_ScriptFullPath%"
;--------------------------开机启动 结束------------------

mac := RegExReplace(GetMacAddress(),"-",":")

;检查配置文件
IfExist, %A_ScriptDir%\ipinfo.ini
{
	IniRead, ip, %A_ScriptDir%\ipinfo.ini, ipinfo, ip
	IniRead, netmask, %A_ScriptDir%\ipinfo.ini, ipinfo, netmask
	IniRead, gateway, %A_ScriptDir%\ipinfo.ini, ipinfo, gateway
	IniRead, dns, %A_ScriptDir%\ipinfo.ini, ipinfo, dns
}
else
{
	MsgBox, 4112, 错误, %A_ScriptDir%\ipinfo.ini 文件不存在,已生成,请修改后再使用!
	IniWrite, ip, %A_ScriptDir%\ipinfo.ini, ipinfo, ip
	IniWrite, 子网掩码, %A_ScriptDir%\ipinfo.ini, ipinfo, netmask
	IniWrite, 默认网关, %A_ScriptDir%\ipinfo.ini, ipinfo, gateway
	IniWrite, dns, %A_ScriptDir%\ipinfo.ini, ipinfo, dns
	ExitApp
}

adaptors := GetAdaptors() ;获取网卡列表
for id,adaptor in adaptors
{
	if(adaptor.mac = mac)
	{
		name := adaptor.name
		Runwait, %ComSpec% /c netsh interface ip set address name=`"%name%`" source=static addr=%ip% mask=%netmask% gateway=%gateway% gwmetric=1, , Hide
		RunWait, %ComSpec% /c netsh interface ip set dns name=`"%name%`" source=static addr=%dns%, ,Hide
	}
}


GetAdaptors(){
    adaptors := {}
	ipconfig := cmd("ipconfig /all") ;cmd方式兼容XP
	lines := StrSplit(ipconfig,"`n","`r")
	aid = 0
	for id,line in Lines
	{
		if (!RegExMatch(line,"^\s*$"))
		{
			if RegExMatch(line, "^.*(适配器|adapter)\s([^\s].*):$", mn)
			{
				aid++
				adaptors[aid] := {}
				adaptors[aid].name := mn2
			}
			Else
			{
				if RegExMatch(line, "^.*(物理地址|Physical Address).*:\s(\w{2})-(\w{2})-(\w{2})-(\w{2})-(\w{2})-(\w{2})$", mm)
					adaptors[aid].mac := mm2 ":" mm3 ":" mm4 ":" mm5 ":" mm6 ":" mm7
			}
		}
	}
	return adaptors
}

GetMacAddress(){ ;获取当前活动网卡MAC
	res := cmd("getmac /NH")
	RegExMatch(res, ".*?([0-9A-Z].{16})(?!\w\\Device)", mac)
	return %mac1%
}


cmd(sCmd, sEncoding:="CP0", sDir:="", ByRef nExitCode:=0) {
    DllCall( "CreatePipe",           PtrP,hStdOutRd, PtrP,hStdOutWr, Ptr,0, UInt,0 )
    DllCall( "SetHandleInformation", Ptr,hStdOutWr, UInt,1, UInt,1                 )

            VarSetCapacity( pi, (A_PtrSize == 4) ? 16 : 24,  0 )
    siSz := VarSetCapacity( si, (A_PtrSize == 4) ? 68 : 104, 0 )
    NumPut( siSz,      si,  0,                          "UInt" )
    NumPut( 0x100,     si,  (A_PtrSize == 4) ? 44 : 60, "UInt" )
    NumPut( hStdOutWr, si,  (A_PtrSize == 4) ? 60 : 88, "Ptr"  )
    NumPut( hStdOutWr, si,  (A_PtrSize == 4) ? 64 : 96, "Ptr"  )

    If ( !DllCall( "CreateProcess", Ptr,0, Ptr,&sCmd, Ptr,0, Ptr,0, Int,True, UInt,0x08000000
                                  , Ptr,0, Ptr,sDir?&sDir:0, Ptr,&si, Ptr,&pi ) )
        Return ""
      , DllCall( "CloseHandle", Ptr,hStdOutWr )
      , DllCall( "CloseHandle", Ptr,hStdOutRd )

    DllCall( "CloseHandle", Ptr,hStdOutWr ) ; The write pipe must be closed before reading the stdout.
    While ( 1 )
    { ; Before reading, we check if the pipe has been written to, so we avoid freezings.
        If ( !DllCall( "PeekNamedPipe", Ptr,hStdOutRd, Ptr,0, UInt,0, Ptr,0, UIntP,nTot, Ptr,0 ) )
            Break
        If ( !nTot )
        { ; If the pipe buffer is empty, sleep and continue checking.
            Sleep, 100
            Continue
        } ; Pipe buffer is not empty, so we can read it.
        VarSetCapacity(sTemp, nTot+1)
        DllCall( "ReadFile", Ptr,hStdOutRd, Ptr,&sTemp, UInt,nTot, PtrP,nSize, Ptr,0 )
        sOutput .= StrGet(&sTemp, nSize, sEncoding)
    }

    ; * SKAN has managed the exit code through SetLastError.
    DllCall( "GetExitCodeProcess", Ptr,NumGet(pi,0), UIntP,nExitCode )
    DllCall( "CloseHandle",        Ptr,NumGet(pi,0)                  )
    DllCall( "CloseHandle",        Ptr,NumGet(pi,A_PtrSize)          )
    DllCall( "CloseHandle",        Ptr,hStdOutRd                     )
    Return sOutput
}


微信图片半自动自动另存 Autohotkey 2357

作者为 发表

Autohotkey

SaveFolder := "d:\desktop\autosave" ;要保存的位置
global WechatProfileFolder := "D:\Documents\WeChat Files\wxid_xxxxxxx" ;微信个人存档位置,一般在我的文档下面
IfNotExist % SaveFolder
	FileCreateDir % SaveFolder

global TmpImgPath := WechatProfileFolder "\FileStorage\Temp\MM_WeChat_Image.dat"
LastSize := GetTmpImgSize()
LastHWnd := ""
Loop
{
	WinWait, ahk_class ImagePreviewWnd
	{
		WinGet, TmpHwnd, ID, ahk_class ImagePreviewWnd
		if(TmpHwnd<>LastHWnd)
		{
			LastHWnd := TmpHwnd
			while(LastSize <> (TmpSzie := GetTmpImgSize()))
			{
				LastSize :=  GetTmpImgSize()
				Sleep, 500
			}
			FileCopy, % TmpImgPath, % SaveFolder "\" Clipboard ".jpg", 1
			WinClose, ahk_id %TmpHwnd%
		}
		else
			Sleep, 500
	}
}


GetTmpImgSize()
{
	IfExist % TmpImgPath
	{
		FileGetSize, size, % TmpImgPath
		return size
	}
	else
		return 0
}


VaxSIPUserAgentOCX.ocx 软电话控件简单使用 AutoHotkey 1597

作者为 发表

AutohotkeyVOIP

首先从网上下载VaxSIPUserAgentOCX.ocx (版本7.0.4.8) 参见:http://www.pudn.com/Download/item/id/853476.html

然后执行:

regsvr32 /s VaxSIPUserAgentOCX.ocx

进行控件注册,注册后还需要有SIP账号,此版本控件经测试支持局域网拨打,互联网拨打NAT转换地址会有问题,服务器端显示离线。

Gui Add, ActiveX, x0 y0 w0 h0 vVaxSIPUserAgentOCX, {2935849A-3F6A-4DF8-8395-CF9AB3BE1835}
Gui, Add, text, x0 y10 w20 h20, IP
Gui, Add, Edit, x20 y10 w170 h20 vip, 192.168.1.2
Gui, Add, text, x200 y10 w30 h20, Port
Gui, Add, Edit, x230 y10 w70 h20 vport, 5060
Gui, Add, Button, x300 y10 w100 h20 gconnect, 连接
Gui, Add, Button, x400 y10 w100 h20 gclose, 关闭
Gui, Add, Button, x500 y10 w100 h20 ganswer, 接听
Gui, Add, Button, x600 y10 w100 h20 ghangup, 挂断
Gui, Add, Button, x600 y10 w100 h20 greject, 拒接

Gui, Add, Edit, x0 y40 w100 h20 vphone,
Gui, Add, Button, x100 y40 w100 h20 gcall, 拨打

Gui, Add, Button, x0 y70 w100 h20 gtransfer, 转接
Gui, Add, Button, x100 y70 w100 h20 ghold, 保持

Gui, Add, ListView, x0 y100 w800 h600 vlv, ID|Type|Msg
gui, Show
ComObjConnect(VaxSIPUserAgentOCX, VaxSIPUserAgentOCX_Events)
LV_ModifyCol(2,100)
LV_ModifyCol(3,1000)
global id,lv,phone,VaxSIPUserAgentOCX
id := 0
holded := false
VaxSIPUserAgentOCX.SetLicenceKey("VAXVOIP.COM-191P238P55P253P97P229P51P76P-100.") ;设置LicenceKey
;MsgBox % VaxSIPUserAgentOCX.GetMyIP()
;MsgBox % VaxSIPUserAgentOCX.GetAudioInDevTotal()
;MsgBox % VaxSIPUserAgentOCX.GetAudioInDevName(0)
return

connect:
Gui, Submit, NoHide
MyIP := VaxSIPUserAgentOCX.GetMyIP()
;VARIANT_BOOL Initialize(VARIANT_BOOL BindToListenIP, BSTR ListenIP, long ListenPort, BSTR FromURI, BSTR SIPOutBoundProxy, BSTR SIPProxy, BSTR LoginId, BSTR LoginPwd, VARIANT_BOOL UseSoundDevice, long TotalLine);
login := VaxSIPUserAgentOCX.Initialize(false,MyIP,5060,"1010<sip:1010@192.168.1.2>","","192.168.1.2","1001","password",True,1)
VaxSIPUserAgentOCX.OpenLine(0, False, MyIP, 7000) ;打开1号通道
VaxSIPUserAgentOCX.RegisterToProxy(3600) ;注册间隔
VaxSIPUserAgentOCX.EnableKeepAlive(60) ;保活
MsgBox % (login=-1 ? "登录成功" : "登录失败:" GetErrorMessage()) "!"
return

hold:
holded := !holded
if holded
	VaxSIPUserAgentOCX.HoldLine(0)
else
	VaxSIPUserAgentOCX.UnHoldLine(0)
return

transfer:
GuiControlGet, phone
VaxSIPUserAgentOCX.TransferCall(0,"sip:" phone "@192.168.1.2>")
return

reject:
GuiControlGet, phone
VaxSIPUserAgentOCX.RejectCall("CLI:" phone)
return

answer:
GuiControlGet, phone
VaxSIPUserAgentOCX.AcceptCall(0, "CLI:" phone, 0, 0)
return

hangup:
VaxSIPUserAgentOCX.Disconnect(0)
return

call:
GuiControlGet, phone
MsgBox % VaxSIPUserAgentOCX.Connect(0,"sip:" phone "@192.168.1.2>",0,0)
return

class VaxSIPUserAgentOCX_Events
{
	OnIncomingDiagnostic(MsgSIP,FromIP,FromPort)
	{
		;id++,LV_Add("",id,"OnIncomingDiagnostic:" FromIP,MsgSIP) //调试SIP消息 消息太多不作显示
	}
	OnOutgoingDiagnostic(MsgSIP,ToIP,ToPort)
	{
		;id++,LV_Add("",id,"OnIncomingDiagnostic:" ToIP,MsgSIP)
	}
	OnTryingToReRegister()
	{
		id++,LV_Add("",id,"OnTryingToReRegister")
	}
	OnSuccessToReRegister()
	{
		id++,LV_Add("",id,"OnTryingToReRegister")
	}
	OnFailToRegister()
	{
		id++,LV_Add("",id,"OnFailToRegister")
	}
	OnFailToReRegister()
	{
		id++,LV_Add("",id,"OnFailToReRegister")
	}
	OnIncomingCall(CallId,DisplayName,UserName,FromURI,ToURI) ;来电
	{
		id++,LV_Add("",id,"OnIncomingCall", CallId)
		GuiControl, , phone, % CallId
		SoundBeep, , 500
	}
	OnDisconnectCall(LineNo)
	{
		id++,LV_Add("",id,"OnDisconnectCall", LineNo)
	}

}

GuiClose:
close:
VaxSIPUserAgentOCX.UnInitialize()
ExitApp

GetErrorMessage()
{
	ErrNo = VaxSIPUserAgentOCX.GetVaxObjectError()
	if(ErrNo = 10)
		return "You are not Online, please click the 'Online' button first."
	if(ErrNo = 11)
		return "Cann't open local communication port. Another softphone (x-Ten, x-lite or skype etc) is already running. Please close it first."
	if(ErrNo = 12)
		return "License Key is not valid."
	if(ErrNo = 13)
		return "Fail to initialize VaxVoIP task window."
	if(ErrNo = 14)
		return "Cann't access Input/Mic device or device is already in use."
	if(ErrNo = 15)
		return "Cann't access Output/Speaker device or device is already in use."
	if(ErrNo = 16)
		return "Input/Mic device is not open."
	if(ErrNo = 17)
		return "Output/Speaker device is not open."
	if(ErrNo = 18)
		return "Your sound device does not support mic volume."
	if(ErrNo = 19)
		return "Your sound device does not support speaker volume."
	if(ErrNo = 20)
		return "Recording media initialization fail."
	if(ErrNo = 21)
		return "Cann't open the wave file."
	if(ErrNo = 22)
		return "Provided SIP URI is not valid."
	if(ErrNo = 23)
		return "Codec is not supported."
	if(ErrNo = 24)
		return "Error to create SDP (Session Description Protocol) request."
	if(ErrNo = 25)
		return "Error to create CONNECTION request. Please check the provided SIP URI is valid."
	if(ErrNo = 26)
		return "Error to create REGISTER request. Please check the provided SIP URI is valid."
	if(ErrNo = 27)
		return "Error to create UN-REGISTER request. Please check the provided SIP URI is valid."
	if(ErrNo = 28)
		return "Error to create DISCONNECT request."
	if(ErrNo = 29)
		return "Line No is not valid."
	if(ErrNo = 30)
		return "Line is already busy."
	if(ErrNo = 31)
		return "Line is not open."
	if(ErrNo = 32)
		return "Invalid Call-Id."
	if(ErrNo = 33)
		return "Provided value is not valid."
	if(ErrNo = 34)
		return "Selected line is not in voice session."
	if(ErrNo = 35)
		return "Fail to read wave file."
	if(ErrNo = 36)
		return "Fail to write wave file."
	if(ErrNo = 37)
		return "Unsupported wave file format."
}

以下是该库的接口定义:

// Generated .IDL file (by the OLE/COM Object Viewer)
// 
// typelib filename: VaxSIPUserAgentOCX.ocx

[
  uuid(148188FB-A6D9-48BC-AE37-65786376CD8E),
  version(1.0),
  helpstring("VaxSIPUserAgentOCX ActiveX Control module"),
  helpfile("VaxSIPUserAgentOCX.hlp"),
  helpcontext(00000000),
  custom(DE77BA64-517C-11D1-A2DA-0000F8773CE9, 83951780),
  custom(DE77BA63-517C-11D1-A2DA-0000F8773CE9, 1246968603)

]
library VAXSIPUSERAGENTOCXLib
{
    // TLib : OLE Automation : {00020430-0000-0000-C000-000000000046}
    importlib("stdole2.tlb");

    // Forward declare all types defined in this typelib
    dispinterface _DVaxSIPUserAgentOCX;
    dispinterface _DVaxSIPUserAgentOCXEvents;

    [
      uuid(9858F01E-3474-40B6-996B-7867195B6A6C),
      helpstring("Dispatch interface for VaxSIPUserAgentOCX Control"),
      hidden
    ]
    dispinterface _DVaxSIPUserAgentOCX {
        properties:
        methods:
            [id(0x00000001)]
            void UnInitialize();
            [id(0x00000002)]
            VARIANT_BOOL SetLicenceKey(BSTR LicenceKey);
            [id(0x00000003)]
            long GetVaxObjectError();
            [id(0x00000004)]
            VARIANT_BOOL CloseLine(long LineNo);
            [id(0x00000005)]
            VARIANT_BOOL Connect(
                            long LineNo, 
                            BSTR ToURI, 
                            long InputDeviceId, 
                            long OutputDeviceId);
            [id(0x00000006)]
            VARIANT_BOOL Disconnect(long LineNo);
            [id(0x00000007)]
            VARIANT_BOOL AcceptCall(
                            long LineNo, 
                            BSTR CallId, 
                            long InputDeviceId, 
                            long OutputDeviceId);
            [id(0x00000008)]
            VARIANT_BOOL RejectCall(BSTR CallId);
            [id(0x00000009)]
            VARIANT_BOOL TransferCall(
                            long LineNo, 
                            BSTR ToURI);
            [id(0x0000000a)]
            VARIANT_BOOL HoldLine(long LineNo);
            [id(0x0000000b)]
            VARIANT_BOOL UnHoldLine(long LineNo);
            [id(0x0000000c)]
            VARIANT_BOOL RegisterToProxy(long Expire);
            [id(0x0000000d)]
            VARIANT_BOOL UnRegisterToProxy();
            [id(0x0000000e)]
            VARIANT_BOOL IsLineOpen(long LineNo);
            [id(0x0000000f)]
            VARIANT_BOOL IsLineHold(long LineNo);
            [id(0x00000010)]
            VARIANT_BOOL IsLineBusy(long LineNo);
            [id(0x00000011)]
            VARIANT_BOOL EnableKeepAlive(long Seconds);
            [id(0x00000012)]
            void DisableKeepAlive();
            [id(0x00000013)]
            void DeselectAllVoiceCodec();
            [id(0x00000014)]
            void SelectAllVoiceCodec();
            [id(0x00000015)]
            VARIANT_BOOL SelectVoiceCodec(long CodecNo);
            [id(0x00000016)]
            VARIANT_BOOL DeselectVoiceCodec(long CodecNo);
            [id(0x00000017)]
            BSTR GetMyIP();
            [id(0x00000018)]
            VARIANT_BOOL DigitDTMF(
                            long LineNo, 
                            BSTR Digit);
            [id(0x00000019)]
            VARIANT_BOOL MuteMic(VARIANT_BOOL Mute);
            [id(0x0000001a)]
            VARIANT_BOOL MuteSpk(VARIANT_BOOL Mute);
            [id(0x0000001b)]
            long GetMicVolume();
            [id(0x0000001c)]
            VARIANT_BOOL SetMicVolume(long Volume);
            [id(0x0000001d)]
            long GetSpkVolume();
            [id(0x0000001e)]
            VARIANT_BOOL SetSpkVolume(long Volume);
            [id(0x0000001f)]
            VARIANT_BOOL EnableMicBoost();
            [id(0x00000020)]
            VARIANT_BOOL DisableMicBoost();
            [id(0x00000021)]
            VARIANT_BOOL IsMicBoostEnable();
            [id(0x00000022)]
            VARIANT_BOOL EnableAGC(long Level);
            [id(0x00000023)]
            VARIANT_BOOL DisableAGC();
            [id(0x00000024)]
            VARIANT_BOOL EnableEchoNoiseCancellation();
            [id(0x00000025)]
            VARIANT_BOOL DisableEchoNoiseCancellation();
            [id(0x00000026)]
            VARIANT_BOOL IsRecording(long LineNo);
            [id(0x00000027)]
            VARIANT_BOOL StopRecording(long LineNo);
            [id(0x00000028)]
            VARIANT_BOOL ResetRecording(long LineNo);
            [id(0x00000029)]
            VARIANT_BOOL SaveRecordingToWaveFile(
                            long LineNo, 
                            BSTR FileName);
            [id(0x0000002a)]
            VARIANT_BOOL IsWaveFilePlaying(long LineNo);
            [id(0x0000002b)]
            VARIANT_BOOL PlayWaveOpen(
                            long LineNo, 
                            BSTR FileName);
            [id(0x0000002c)]
            VARIANT_BOOL PlayWaveSkipTo(
                            long LineNo, 
                            long Seconds);
            [id(0x0000002d)]
            long PlayWaveTotalTime(long LineNo);
            [id(0x0000002e)]
            VARIANT_BOOL PlayWavePause(long LineNo);
            [id(0x0000002f)]
            VARIANT_BOOL PlayWaveStart(
                            long LineNo, 
                            VARIANT_BOOL Listen);
            [id(0x00000030)]
            VARIANT_BOOL PlayWaveStop(long LineNo);
            [id(0x00000031)]
            long PlayWavePosition(long LineNo);
            [id(0x00000032)]
            void EnableDonotDisturb();
            [id(0x00000033)]
            void DisableDonotDisturb();
            [id(0x00000034)]
            VARIANT_BOOL SetTOS(
                            long LineNo, 
                            long Value);
            [id(0x00000035)]
            long GetTOS(long LineNo);
            [id(0x00000036)]
            VARIANT_BOOL EnableForceInbandDTMF(long LineNo);
            [id(0x00000037)]
            VARIANT_BOOL DisableForceInbandDTMF(long LineNo);
            [id(0x00000038)]
            VARIANT_BOOL SetDTMFVolume(long Volume);
            [id(0x00000039)]
            long GetDTMFVolume();
            [id(0x0000003a)]
            VARIANT_BOOL Initialize(
                            VARIANT_BOOL BindToListenIP, 
                            BSTR ListenIP, 
                            long ListenPort, 
                            BSTR FromURI, 
                            BSTR SIPOutBoundProxy, 
                            BSTR SIPProxy, 
                            BSTR LoginId, 
                            BSTR LoginPwd, 
                            VARIANT_BOOL UseSoundDevice, 
                            long TotalLine);
            [id(0x0000003b)]
            VARIANT_BOOL StartRecording(
                            long LineNo, 
                            long RecordVoice, 
                            VARIANT_BOOL RecordCompress);
            [id(0x0000003c)]
            long GetMicSoundLevel();
            [id(0x0000003d)]
            long GetSpkSoundLevel();
            [id(0x0000003e)]
            long GetOutboundCodec(long LineNo);
            [id(0x0000003f)]
            long GetInboundCodec(long LineNo);
            [id(0x00000040)]
            VARIANT_BOOL OpenLine(
                            long LineNo, 
                            VARIANT_BOOL BindToRTPRxIP, 
                            BSTR RTPRxIP, 
                            long RTPRxPort);
            [id(0x00000041)]
            long GetAudioInDevTotal();
            [id(0x00000042)]
            long GetAudioOutDevTotal();
            [id(0x00000043)]
            BSTR GetAudioOutDevName(long DeviceId);
            [id(0x00000044)]
            BSTR GetAudioInDevName(long DeviceId);
            [id(0x00000045)]
            BSTR GetVersionSDK();
            [id(0x00000046)]
            BSTR GetVersionFile();
            [id(0x00000047)]
            VARIANT_BOOL JoinTwoLine(
                            long LineNoA, 
                            long LineNoB);
    };

    [
      uuid(747FAA95-5D00-4EA1-9F1F-035D2A88FDA4),
      helpstring("Event interface for VaxSIPUserAgentOCX Control")
    ]
    dispinterface _DVaxSIPUserAgentOCXEvents {
        properties:
        methods:
            [id(0x00000001)]
            void OnIncomingDiagnostic(
                            BSTR MsgSIP, 
                            BSTR FromIP, 
                            long FromPort);
            [id(0x00000002)]
            void OnOutgoingDiagnostic(
                            BSTR MsgSIP, 
                            BSTR ToIP, 
                            long ToPort);
            [id(0x00000003)]
            void OnDTMFDigit(
                            long LineNo, 
                            BSTR Digit);
            [id(0x00000004)]
            void OnPlayWaveDone(long LineNo);
            [id(0x00000005)]
            void OnMsgNOTIFY(BSTR Msg);
            [id(0x00000006)]
            void OnTryingToUnRegister();
            [id(0x00000007)]
            void OnFailToUnRegister();
            [id(0x00000008)]
            void OnSuccessToUnRegister();
            [id(0x00000009)]
            void OnTryingToRegister();
            [id(0x0000000a)]
            void OnFailToRegister();
            [id(0x0000000b)]
            void OnSuccessToRegister();
            [id(0x0000000c)]
            void OnFailToConnect(long LineNo);
            [id(0x0000000d)]
            void OnConnecting(long LineNo);
            [id(0x0000000e)]
            void OnIncomingCallRingingStart(BSTR CallId);
            [id(0x0000000f)]
            void OnIncomingCallRingingStop(BSTR CallId);
            [id(0x00000010)]
            void OnDisconnectCall(long LineNo);
            [id(0x00000011)]
            void OnCallTransferAccepted(long LineNo);
            [id(0x00000012)]
            void OnProvisionalResponse(
                            long LineNo, 
                            long StatusCode, 
                            BSTR ReasonPhrase);
            [id(0x00000013)]
            void OnRedirectionResponse(
                            long LineNo, 
                            long StatusCode, 
                            BSTR ReasonPhrase, 
                            BSTR Contact);
            [id(0x00000014)]
            void OnRequestFailureResponse(
                            long LineNo, 
                            long StatusCode, 
                            BSTR ReasonPhrase);
            [id(0x00000015)]
            void OnServerFailureResponse(
                            long LineNo, 
                            long StatusCode, 
                            BSTR ReasonPhrase);
            [id(0x00000016)]
            void OnGeneralFailureResponse(
                            long LineNo, 
                            long StatusCode, 
                            BSTR ReasonPhrase);
            [id(0x00000017)]
            void OnSuccessToConnect(
                            long LineNo, 
                            BSTR ToRTPIP, 
                            long ToRTPPort);
            [id(0x00000018)]
            void OnIncomingCall(
                            BSTR CallId, 
                            BSTR DisplayName, 
                            BSTR UserName, 
                            BSTR FromURI, 
                            BSTR ToURI);
            [id(0x00000019)]
            void OnVoiceMailMsg(
                            VARIANT_BOOL IsMsgWaiting, 
                            long NewMsgCount, 
                            long OldMsgCount, 
                            long NewUrgentMsgCount, 
                            long OldUrgentMsgCount, 
                            BSTR MsgAccount);
            [id(0x0000001a)]
            void OnTryingToReRegister();
            [id(0x0000001b)]
            void OnFailToReRegister();
            [id(0x0000001c)]
            void OnSuccessToReRegister();
    };

    [
      uuid(2935849A-3F6A-4DF8-8395-CF9AB3BE1835),
      helpstring("VaxSIPUserAgentOCX Control"),
      control
    ]
    coclass VaxSIPUserAgentOCX {
        [default] dispinterface _DVaxSIPUserAgentOCX;
        [default, source] dispinterface _DVaxSIPUserAgentOCXEvents;
    };
};


获取MySQL(或其他服务)执行程序路径 Autohotkey 994

作者为 发表

Autohotkey

;获取mysql目录
srvPath := ""
for srv in ComObjGet("winmgmts:").ExecQuery("select * from CIM_Service where Name like '%mysql%'")
{
	try
		tp := srv.PathName
	if tp
	{
		if RegExMatch(tp,"^""([^""]*bin\\)[^""]*""", m) ;匹配路径规则
		{
			srvPath := m1
			break
		}
	}
}


在ado中使用ODBC的dsn连接Oracle、Mysql等数据库 Autohotkey 6252

作者为 发表

Autohotkey

ODBC驱动可以搜索“数据库类型 windows ODBC 插件”安装;DSN需要在开始菜单,Windows管理工具中找“ODBC 数据源(32 位)”,此处如果用32位的AHK则用32位的版本添加,不然无法访问。

a := new adodb
a.open("DSN=testdb;UID=thinkai;PWD=password;") ;到DSN里面配置了用户名密码则UID PWD不用配置。
ret := a.GetTable("select getdate()")
MsgBox % ret.1.1

class adodb
{
	;static conn

	__New() ;新建
	{
	this.conn:= ComObjCreate("ADODB.connection") ;初始化COM
	}

	open(connect_str) ;打开文件
	{
		try
			this.conn.Open(connect_str)
		catch e
			return e.Message
	}

	close() ;关闭文件
	{
		this.conn.Close()
	}

	GetTable(sql)
	{
		t := []
		query := this.conn.Execute(sql)
		if RegExMatch(sql,"i)^select*")
		{
			try
			{
				fetchedArray := query.GetRows() ;取出数据(二维数组)
				colSize := fetchedArray.MaxIndex(1) + 1 ;列最大值 tips:从0开始 所以要+1
				rowSize := fetchedArray.MaxIndex(2) + 1 ;行最大值 tips:从0开始 所以要+1
				loop, % rowSize
				{
					i := (y := A_index) - 1
					t[y] := []
					loop, % colSize
					{
						j := (x := A_index) - 1
						t[y][x] := fetchedArray[j,i] ;取出二维数组内值
					}
				}
			}
			query.Close()
			return t
		}
	}
}


Class_MySQLAPI.ahk及简单测试 Autohotkey 2200

作者为 发表

Autohotkey

#Include Class_MySQLAPI.ahk
#NoEnv
My_DB := New MySQLAPI         
My_DB.Real_Connect("127.0.0.1", "root", "pass","db1")    ;主机,用户名,密码,数据库               
SQL := "SELECT now() as nowtime,1 as Status" ;语句
Result := My_DB.Query(SQL) ;查询
MsgBox % var_dump(My_DB.GetResult()) ;获取数组结果

var_dump(obj,level:=0){
    static id,str
	id++
    if id=1
        str := ""
    if IsObject(obj)
    {
        space =
        loop % level
            space .= A_Tab
        str .= space "{`n"
        for k,v in obj
        {
            if IsObject(v)
            {
                str .= space A_Tab (RegExMatch(k,"^\d+$") ? k : """" k """") ":`n"
                var_dump(v,level+1)
                str := RegExReplace(str,"(*ANYCRLF)\n$",",`n")
            }
            else
                str .= space A_Tab (RegExMatch(k,"^\d+$") ? k : """" k """") ":""" RegExReplace(v,"""","""""") """,`n"
        }
        str := RegExReplace(str,"(*ANYCRLF),\n*$","`n")
        str .= space "}`n"
    }
    else
        str := obj
    if !level
		id := 0
	return str
}


Class_MySQLAPI.ahk(需要libmysql.dll):

; ======================================================================================================================
; Wrapper class for MySQL C API functions        -> http://dev.mysql.com/doc/refman/5.5/en/c-api-functions.html
; Based on "MySQL Library functions" by panofish -> http://www.autohotkey.com/board/topic/72629-mysql-library-functions
; Namespace:   MySQLAPI
; AHK version: 1.1.10+
; Author:      panofish/just me
; Version:     1.0.01.00/2015-08-20/just me        - libmysql.dll error handling
;              1.0.00.00/2013-06-15/just me
;
; Example usage:
;    #Include <Class_MySQLAPI>                                       ; include Class_MySQLAPI.ahk from lib
;    My_DB := New MySQLAPI                                           ; instantiate an object using this class
;    My_DB.Connect("Server", "User", "Password")                     ; connect to the server
;    My_DB.Select_DB("Database")                                     ; select a database
;    or
;    My_DB.Real_Connect("Server", "User", "Password", "Database")    ; connect to the server and select a database
;    SQL := "SELECT ..."                                             ; create a SQL statement
;    Result := My_DB.Query(SQL)                                      ; execute the SQL statement
;    ...                                                             ; do something
;    ...                                                             ; do another thing
;    My_DB := ""                                                     ; close the connection and free all resources
;
; Remarks:
; The character encoding depends on the character set used by the current connection. That's why the code page for
; all connections is set to UTF-8 within the __New() meta-function. String conversions are done internally
; whenever possible.
; ======================================================================================================================
Class MySQLAPI {
   ; ===================================================================================================================
   ; CLASS VARIABLES
   ; ===================================================================================================================
   ; MYSQL_FIELD type
   Static FIELD_TYPE := {0: "DECIMAL", 1: "TINY", 2: "SHORT", 3: "LONG", 4: "FLOAT", 5: "DOUBLE", 6: "NULL"
                       , 7: "TIMESTAMP", 8: "LONGLONG", 9: "INT24", 10: "DATE", 11: "TIME", 12: "DATETIME"
                       , 13: "YEAR", 14: "NEWDATE", 15: "VARCHAR", 16: "BIT", 256: "NEWDECIMAL", 247: "ENUM"
                       , 248: "SET", 249: "TINY_BLOB", 250: "MEDIUM_BLOB", 251: "LONG_BLOB", 252: "BLOB"
                       , 253: "VAR_STRING", 254: "STRING", 255: "GEOMETRY"}
   ; MYSQL_FIELD bit-flags
   Static FIELD_FLAG := {NOT_NULL: 1, PRI_KEY: 2, UNIQUE_KEY: 4, MULTIPLE_KEY: 8, BLOB: 16, UNSIGNED: 32
                       , ZEROFILL: 64, BINARY: 128, ENUM: 256, AUTO_INCREMENT: 512, TIMESTAMP: 1024, SET: 2048
                       , NO_DEFAULT_VALUE: 4096, NUM:	32768}
   ; MySQL_SUCCESS
   Static MySQL_SUCCESS := 0
   ; ===================================================================================================================
   ; META FUNCTION __New
   ; Load and initialize libmysql.dll which is supposed to be in the sript's folder.
   ; Parameters:    LibPath  - Optional: Absolute path of libmysql.dll
   ; ===================================================================================================================
   __New(LibPath := "") {
      Static LibMySQL := A_ScriptDir . "\libmysql.dll"
      ; Do not instantiate unstances!
      If (This.Base.Base.__Class = "MySQLAPI") {
         MsgBox, 16, MySQL Error!, You must not instantiate instances of MySQLDB!
         Return False
      }
      ; Load libmysql.dll
      If (LibPath)
         LibMySQL := LibPath
      If !(MySQLM := DllCall("Kernel32.dll\LoadLibrary", "Str", LibMySQL, "UPtr")) {
         If (A_LastError = 126) ; The specified module could not be found
            MsgBox, 16, MySQL Error!, Could not find %LibMySQL%!
         Else {
            ErrCode := A_LastError
            VarSetCapacity(ErrMsg, 131072, 0) ; Unicode
            DllCall("FormatMessage", "UInt", 0x1200, "Ptr", 0, "UInt", ErrCode, "UInt", 0, "Str", ErrMsg, "UInt", 65536, "Ptr", 0)
            MsgBox, 16, MySQL Error!, % "Could not load " . LibMySQL . "!`n"
                                      . "Error code: " . ErrCode . "`n"
                                      . ErrMsg
         }
         Return False
      }
      This.Module := MySQLM
      ; Init MySQL
      If !(MYSQL := This.Init()) {
         MsgBox, 16, MySQL Error!, Could not initialize MySQL!
         Return False
      }
      This.MYSQL := MYSQL
      If (This.Options("MYSQL_SET_CHARSET_NAME", "utf8") <> This.MySQL_SUCCESS) {
         MsgBox, 16, MySQL Error!, Set option MYSQL_SET_CHARSET_NAME failed!
         Return False
      }
      If (This.Options("MYSQL_OPT_RECONNECT", True) <> This.MySQL_SUCCESS) {
         MsgBox, 16, MySQL Error!, Set option MYSQL_OPT_RECONNECT failed!
         Return False
      }
      This.Connected := False
   }
   ; ===================================================================================================================
   ; META FUNCTION __Delete
   ; Free ressources and close the connection, if needed.
   ; ===================================================================================================================
   __Delete() {
      If (This.MYSQL)
         This.Close()
      If (This.Module)
         DllCall("Kernel32.dll\FreeLibrary", "Ptr", This.Module)
   }
   ; ===================================================================================================================
   ; ===================================================================================================================
   ; ===================================================================================================================
   ; Additional custom functions to get the data of a MYSQL_RES structure
   ; ===================================================================================================================
   ; ===================================================================================================================
   ; ===================================================================================================================
   ; Converts a MYSQL_FIELD structure and returns an object containing the appropriate keys and values.
   ; Parameters:    MYSQL_FIELD - Pointer to a MYSQL_FIELD structure.
   ; Return values: Field object.
   ; ===================================================================================================================
   GetField(ByRef MYSQL_FIELD) {
      Field := {}
      Offset := 0
      Field.Name      := StrGet(NumGet(MYSQL_FIELD + 0, Offset, "UPtr"), "UTF-8"), Offset += A_PtrSize
      Field.OrgName   := StrGet(NumGet(MYSQL_FIELD + 0, Offset, "UPtr"), "UTF-8"), Offset += A_PtrSize
      Field.Table     := StrGet(NumGet(MYSQL_FIELD + 0, Offset, "UPtr"), "UTF-8"), Offset += A_PtrSize
      Field.OrgTable  := StrGet(NumGet(MYSQL_FIELD + 0, Offset, "UPtr"), "UTF-8"), Offset += A_PtrSize
      Field.DB        := StrGet(NumGet(MYSQL_FIELD + 0, Offset, "UPtr"), "UTF-8"), Offset += A_PtrSize
      Field.Catalog   := StrGet(NumGet(MYSQL_FIELD + 0, Offset, "UPtr"), "UTF-8"), Offset += A_PtrSize
      Field.Default   := StrGet(NumGet(MYSQL_FIELD + 0, Offset, "UPtr"), "UTF-8"), Offset += A_PtrSize
      Field.Length    := NumGet(MYSQL_FIELD + 0, Offset, "UInt"), Offset += 4
      Field.MaxLength := NumGet(MYSQL_FIELD + 0, Offset, "UInt"), Offset += 4 * 8 ; skip string length fields
      Field.Flags     := NumGet(MYSQL_FIELD + 0, Offset, "UInt"), Offset += 4
      Field.Decimals  := NumGet(MYSQL_FIELD + 0, Offset, "UInt"), Offset += 4
      Field.CharSetNr := NumGet(MYSQL_FIELD + 0, Offset, "UInt"), Offset += 4
      Field.Type      := This.FIELD_TYPE[NumGet(MYSQL_FIELD + 0, Offset, "UInt")]
      Return Field
   }
   ; ===================================================================================================================
   ; Returns the values of the next row of the given MYSQL_RES as an array.
   ; Parameters:    MYSQL_RES - Pointer to a MYSQL_RES structure.
   ; Return values: Array of values, False if there is no more row
   ; ===================================================================================================================
   GetNextRow(MYSQL_RES) {
      If (MYSQL_ROW := This.Fetch_Row(MYSQL_RES)) {
         Row := []
         Lengths := This.Fetch_Lengths(MYSQL_RES)
         Loop, % This.Num_Fields(MYSQL_RES) {
            J := A_Index - 1
            If (Len := NumGet(Lengths + 0, 4 * J, "UInt"))
               Row[A_Index] := (StrGet(NumGet(MYSQL_ROW + 0, A_PtrSize * J, "UPtr"), Len, "UTF-8"))
            Else
               Row[A_Index] := ""
         }
         Return Row
      }
      Return False
   }
   ; ===================================================================================================================
   ; Gets the result for the most recent query that successfully produced a result set and returns an object containing
   ; the appropriate keys and values.
   ; Return values: Result object, or False if there is no result.
   ; ===================================================================================================================
   GetResult() {
      If !(MYSQL_RES := This.Store_Result(This.MYSQL))
            Return False
      Result := {}
      Result.Rows := This.Num_Rows(MYSQL_RES)
      Result.Columns := This.Num_Fields(MYSQL_RES)
      Result.Fields := []
      While(MYSQL_FIELD := This.Fetch_Field(MYSQL_RES))
         Result.Fields[A_Index] := This.GetField(MYSQL_FIELD)
      While (Row := This.GetNextRow(MYSQL_RES))
         Result[A_index] := Row
      This.Free_Result(MYSQL_RES)
      Return Result
   }
   GetResultLite() {
      If !(MYSQL_RES := This.Store_Result(This.MYSQL))
            Return False
      Result := {}
     ; Result.Rows := This.Num_Rows(MYSQL_RES)
     ; Result.Columns := This.Num_Fields(MYSQL_RES)
     ; Result.Fields := []
     ; While(MYSQL_FIELD := This.Fetch_Field(MYSQL_RES))
     ;    Result.Fields[A_Index] := This.GetField(MYSQL_FIELD)
      While (Row := This.GetNextRow(MYSQL_RES))
         Result[A_index] := Row
      This.Free_Result(MYSQL_RES)
      Return Result
   }
   ; ===================================================================================================================
   ; Converts the passed string to UTF-8.
   ; Parameters:    Str - String to convert.
   ; Return values: Address of Str.
   ; ===================================================================================================================
   UTF8(ByRef Str) {
      Var := Str, VarSetCapacity(Str, StrPut(Var, "UTF-8"), 0), StrPut(Var, &Str, "UTF-8")
      Return &Str
   }
   ; ===================================================================================================================
   ; ===================================================================================================================
   ; ===================================================================================================================
   ; API functions
   ; ===================================================================================================================
   ; ===================================================================================================================
   ; ===================================================================================================================
   ; May be called immediately after executing a statement with mysql_query() or mysql_real_query(). It returns the
   ; number of rows changed, deleted, or inserted by the last statement if it was an UPDATE, DELETE, or INSERT.
   ; Return values: An integer greater than zero indicates the number of rows affected or retrieved.
   ; ===================================================================================================================
   Affected_Rows() {
      Return DllCall("libmysql.dll\mysql_affected_rows", "Ptr", This.MYSQL, "UInt64")
   }
   ; ===================================================================================================================
   ; Sets autocommit mode on if Mode is 1, off if Mode is 0.
   ; Parameters:    Mode  - 0/1 (False/True)
   ; Return values: Zero if successful. Nonzero if an error occurred.
   ; ===================================================================================================================
   AutoCommit(Mode) {
      Return DllCall("libmysql.dll\mysql_autocommit", "Ptr", This.MYSQL, "Char", Mode, "Char")
   }
   ; ===================================================================================================================
   ; Changes the user and causes the database specified by DB to become the default (current) database on the connection
   ; specified by mysql.
   ; Parameters:    User     - User name
   ;                PassWd   - Password
   ;                DB       - Database name
   ; Return values: Zero if successful. Nonzero if an error occurred.
   ; ===================================================================================================================
   Change_User(User, PassWd, DB) {
      Return DllCall("libmysql.dll\mysql_change_user", "Ptr", This.MYSQL, "Ptr", This.UTF8(User)
                  , "Ptr", This.UTF8(PassWd), "Ptr", This.UTF8(DB), "Char")
   }
   ; ===================================================================================================================
   ; Returns a string containing the default character set name for the current connection.
   ; Return values: String.
   ; ===================================================================================================================
   Character_Set_Name() {
      Return ((P := DllCall("libmysql.dll\mysql_character_set_name", "Ptr", This.MYSQL, "UPtr")) ? StrGet(P, "UTF-8") : "")
   }
   ; ===================================================================================================================
   ; Closes a previously opened connection.
   ; Return values: None
   ; ===================================================================================================================
   Close() {
      DllCall("libmysql.dll\mysql_close", "Ptr", This.MYSQL)
   }
   ; ===================================================================================================================
   ; Commits the current transaction.
   ; Return values: Zero if successful. Nonzero if an error occurred.
   ; ===================================================================================================================
   Commit() {
      Return DllCall("libmysql.dll\mysql_commit", "Ptr", This.MYSQL, "Char")
   }
   ; ===================================================================================================================
   ; This function is deprecated. Use mysql_real_connect() instead.
   ; ===================================================================================================================
   Connect(Host, User, PassWd) {
      Return This.Real_Connect(Host, User, PassWD)
   }
   ; ===================================================================================================================
   ; Creates the database named by the DB parameter.
   ; This function is deprecated. It is preferable to use mysql_query() to issue an SQL CREATE DATABASE statement
   ; instead.
   ; Parameters:    DB    - Database name
   ; Return values: Zero if the database was created successfully. Nonzero if an error occurred.
   ; ===================================================================================================================
   Create_DB(DB) {
      Return DllCall("libmysql.dll\mysql_create_db", "Ptr", This.MYSQL, "Ptr", This.UTF8(DB), "Int")
   }
   ; ===================================================================================================================
   ; Seeks to an arbitrary row in a query result set. The Offset value is a row number.
   ; Parameters:    MYSQL_RES - Pointer to a MYSQL_RES structure
   ;                Offset    - Specify a value in the range from 0 to mysql_num_rows(result)-1.
   ; Return values: None
   ; ===================================================================================================================
   Data_Seek(MYSQL_RES, Offset) {
      DllCall("libmysql.dll\mysql_data_seek", "Ptr", MYSQL_RES, "UInt64", Offset)
   }
   ; ===================================================================================================================
   ; mysql_debug() - not implemented <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
   ; ===================================================================================================================
   ; ===================================================================================================================
   ; Drops the database named by the DB parameter.
   ; This function is deprecated. It is preferable to use mysql_query() to issue an SQL DROP DATABASE statement instead.
   ; Parameters:    DB    - Database name
   ; Return values: Zero if the database was dropped  successfully. Nonzero if an error occurred.
   ; ===================================================================================================================
   Drop_DB(DB) {
      Return DllCall("libmysql.dll\mysql_drop_db", "Ptr", This.MYSQL, "Ptr", This.UTF8(DB), "Int")
   }
   ; ===================================================================================================================
   ; mysql_dump_debug_info() - not implemented <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
   ; ===================================================================================================================
   ; ===================================================================================================================
   ; Determines whether the last row of a result set has been read.
   ; This function is deprecated. mysql_errno() or mysql_error() may be used instead.
   ; Parameters:    MYSQL_RES - Pointer to a MYSQL_RES structure
   ; Return values: Zero if no error occurred. Nonzero if the end of the result set has been reached.
   ; ===================================================================================================================
   EOF(MYSQL_RES) {
      Return DllCall("libmysql.dll\mysql_eof", "Ptr", MYSQL_RES, "Char")
   }
   ; ===================================================================================================================
   ; Returns the error code for the most recently invoked API function that can succeed or fail.
   ; Return values: An error code value for the last mysql_xxx() call, if it failed. zero means no error occurred.
   ; ===================================================================================================================
   ErrNo() {
      Return DllCall("libmysql.dll\mysql_errno", "Ptr", This.MYSQL, "UInt")
   }
   ; ===================================================================================================================
   ; Returns a null-terminated string containing the error message for the most recently invoked API
   ; function that failed. An empty string indicates no error.
   ; Return values: String.
   ; ===================================================================================================================
   Error() {
      Return ((S := DllCall("libmysql.dll\mysql_error", "Ptr", This.MYSQL, "UPtr")) ? StrGet(S, "UTF-8") : "")
   }
   ; ===================================================================================================================
   ; mysql_escape_string() ->  mysql_real_escape_string()
   ; ===================================================================================================================
   ; ===================================================================================================================
   ; Returns the definition of the next column of a result set as a MYSQL_FIELD structure.
   ; Parameters:    MYSQL_RES - Pointer to a MYSQL_RES structure
   ; Return values: A pointer to the MYSQL_FIELD structure for the current column. NULL if no columns are left.
   ; ===================================================================================================================
   Fetch_Field(MYSQL_RES) {
      Return DllCall("libmysql.dll\mysql_fetch_field", "Ptr", MYSQL_RES, "UPtr")
   }
   ; ===================================================================================================================
   ; Given a field number FieldNr for a column within a result set, returns that column's field definition as
   ; a MYSQL_FIELD structure.
   ; Parameters:    MYSQL_RES - Pointer to a MYSQL_RES structure
   ;                FieldNr   - Field number in the range from 0 to mysql_num_fields(result)-1.
   ; Return values: A Pointer to the MYSQL_FIELD structure for the specified column.
   ; ===================================================================================================================
   Fetch_Field_Direct(MYSQL_RES, FieldNr) {
      Return DllCall("libmysql.dll\mysql_fetch_field_direct", "Ptr", MYSQL_RES, "UInt", FieldNr, "UPtr")
   }
   ; ===================================================================================================================
   ; Returns an array of all MYSQL_FIELD structures for a result set. Each structure provides the field definition for
   ; one column of the result set.
   ; Parameters:    MYSQL_RES - Pointer to a MYSQL_RES structure
   ; Return values: A Pointer to the MYSQL_FIELD structure for the specified column.
   ; ===================================================================================================================
   Fetch_Fields(MYSQL_RES) {
      Return DllCall("libmysql.dll\mysql_fetch_fields", "Ptr", MYSQL_RES, "UPtr")
   }
   ; ===================================================================================================================
   ; Returns the lengths of the columns of the current row within a result set.
   ; Parameters:    MYSQL_RES - Pointer to a MYSQL_RES structure
   ; Return values: A Pointer to an array of unsigned long integers representing the size of each column
   ;                (not including any terminating null characters). NULL if an error occurred.
   ; ===================================================================================================================
   Fetch_Lengths(MYSQL_RES) {
      Return DllCall("libmysql.dll\mysql_fetch_lengths", "Ptr", MYSQL_RES, "UPtr")
   }
   ; ===================================================================================================================
   ; Retrieves the next row of a result set.
   ; Parameters:    MYSQL_RES - Pointer to a MYSQL_RES structure
   ; Return values: A poiner to a MYSQL_ROW structure, NULL when there are no more rows to retrieve or if an error
   ;                occurred.
   ; ===================================================================================================================
   Fetch_Row(MYSQL_RES) {
      Return DllCall("libmysql.dll\mysql_fetch_row", "Ptr", MYSQL_RES, "UPtr")
   }
   ; ===================================================================================================================
   ; Returns the number of columns for the most recent query on the connection.
   ; Return values: An unsigned integer representing the number of columns in a result set.
   ; ===================================================================================================================
   Field_Count() {
      Return DllCall("libmysql.dll\mysql_field_count", "Ptr", This.MYSQL, "UInt")
   }
   ; ===================================================================================================================
   ; Sets the field cursor to the given offset. The next call to mysql_fetch_field() retrieves the field definition
   ; of the column associated with that offset.
   ; Parameters:    MYSQL_RES - Pointer to a MYSQL_RES structure
   ;                Offset    - Specify a value in the range from 0 to mysql_num_fields(result)-1.
   ;                            To seek to the beginning of a row, pass an offset value of zero.
   ; Return values: The previous value of the field cursor.
   ; ===================================================================================================================
   Field_Seek(MYSQL_RES, Offset) {
      Return DllCall("libmysql.dll\mysql_field_seek", "Ptr", MYSQL_RES, "UInt", Offset, "UInt")
   }
   ; ===================================================================================================================
   ; Returns the position of the field cursor used for the last mysql_fetch_field(). This value can be used as
   ; an argument to mysql_field_seek().
   ; Parameters:    MYSQL_RES -  Pointer to a MYSQL_RES structure
   ; Return values: The current offset of the field cursor.
   ; ===================================================================================================================
   Field_Tell(MYSQL_RES) {
      Return DllCall("libmysql.dll\mysql_field_tell", "Ptr", MYSQL_RES, "UInt")
   }
   ; ===================================================================================================================
   ; Frees the memory allocated for a result set by mysql_store_result(), mysql_use_result(), and so forth.
   ; Parameters:    MYSQL_RES -  Pointer to a MYSQL_RES structure
   ; Return values: None.
   ; ===================================================================================================================
   Free_Result(MYSQL_RES) {
      DllCall("libmysql.dll\mysql_free_result", "Ptr", MYSQL_RES)
   }
   ; ===================================================================================================================
   ; mysql_get_character_set_info() - not implemented <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
   ; ===================================================================================================================
   ; ===================================================================================================================
   ; Returns a string that represents the client library version.
   ; Parameters:    None
   ; Return values: String.
   ; ===================================================================================================================
   Get_Client_Info() {
      Return ((S := DllCall("libmysql.dll\mysql_get_client_info", "UPtr")) ? StrGet(S, "UTF-8") : "")
   }
   ; ===================================================================================================================
   ; Returns an integer that represents the client library version. The value has the format XYYZZ where X is the major
   ; version, YY is the release level, and ZZ is the version number within the release level. For example, a value of
   ; 40102 represents a client library version of 4.1.2.
   ; Parameters:    None
   ; Return values: An integer that represents the MySQL client library version.
   ; ===================================================================================================================
   Get_Client_Version() {
      Return DllCall("libmysql.dll\mysql_get_client_version", "Int")
   }
   ; ===================================================================================================================
   ; Returns a string describing the type of connection in use, including the server host name.
   ; Return values: String.
   ; ===================================================================================================================
   Get_Host_Info() {
      Return ((P := DllCall("libmysql.dll\mysql_get_host_info", "Ptr", This.MYSQL, "UPtr")) ? StrGet(P, "UTF-8") : "")
   }
   ; ===================================================================================================================
   ; Returns the protocol version used by current connection.
   ; Return values: An unsigned integer representing the protocol version used by the current connection.
   ; ===================================================================================================================
   Get_Proto_Info() {
      Return DllCall("libmysql.dll\mysql_get_proto_info", "Ptr", This.MYSQL, "UInt")
   }
   ; ===================================================================================================================
   ; Returns a string that represents the server version number.
   ; Return values: String.
   ; ===================================================================================================================
   Get_Server_Info() {
      Return ((P := DllCall("libmysql.dll\mysql_get_server_info", "Ptr", This.MYSQL, "UPtr")) ? StrGet(P, "UTF-8") : "")
   }
   ; ===================================================================================================================
   ; Returns the version number of the server as an unsigned integer.
   ; Return values: A number that represents the MySQL server version, for example, 5.1.5 is returned as 50105.
   ; ===================================================================================================================
   Get_Server_Version() {
      Return DllCall("libmysql.dll\mysql_get_server_version", "Ptr", This.MYSQL, "UInt")
   }
   ; ===================================================================================================================
   ; mysql_get_ssl_cipher() - not implemented <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
   ; mysql_hex_string()     - not implemented <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
   ; ===================================================================================================================
   ; ===================================================================================================================
   ; Retrieves a string providing information about the most recently executed statement.
   ; Return values: String.
   ; ===================================================================================================================
   Info() {
      Return ((S := DllCall("libmysql.dll\mysql_info", "Ptr", This.MYSQL, "UPtr")) ? StrGet(S, "UTF-8") : "")
   }
   ; ===================================================================================================================
   ; Allocates or initializes a MYSQL object suitable for mysql_real_connect().
   ; Parameters:    MYSQL - Pointer to a MYSQL structure, pass NULL to allocate a new object
   ; Return values: An initialized MYSQL* handle. NULL if there was insufficient memory to allocate a new object.
   ; ===================================================================================================================
   Init(MYSQL := 0) {
      Return DllCall("libmysql.dll\mysql_init", "Ptr", MYSQL, "UPtr")
   }
   ; ===================================================================================================================
   ; Returns the value generated for an AUTO_INCREMENT column by the previous INSERT or UPDATE statement.
   ; Return values: Generated ID, if any.
   ; ===================================================================================================================
   Insert_ID() {
      Return DllCall("libmysql.dll\mysql_insert_id", "Ptr", This.MYSQL, "UInt64")
   }
   ; ===================================================================================================================
   ; mysql_kill()           - not implemented <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
   ; mysql_library_end()    - not implemented <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
   ; mysql_library_init()   - not implemented <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
   ; mysql_list_dbs()       - not implemented <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
   ; ===================================================================================================================
   ; Returns a result set consisting of field names in the given table that match the expression specified by
   ; the Like parameter.
   ; Parameters:     Table   - Table name
   ;                 Optional: Like - Expression field names have to match
   ;                                  (may contain the wildcard characters '%' or '_')
   ; Return values: A pointer to a MYSQL_RES result set for success. NULL if an error occurred.
   ; ===================================================================================================================
   List_Fields(Table, Like := "") {
      Return DllCall("libmysql.dll\mysql_list_fields", "Ptr", This.MYSQL, "Ptr", This.UTF8(Table)
                   , "Ptr", (Like = "" ? 0 : This.UTF8(Like)), "UPtr")
   }
   ; ===================================================================================================================
   ; mysql_list_processes() - not implemented <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
   ; ===================================================================================================================
   ; ===================================================================================================================
   ; Returns a result set consisting of table names in the current database that match the expression specified
   ; by the Like parameter.
   ; Parameters:     Optional: Like - Expression table names have to match
   ;                                  (may contain the wildcard characters '%' or '_')
   ; Return values: A pointer to a MYSQL_RES result set for success. NULL if an error occurred.
   ; ===================================================================================================================
   List_Tables(Like := "") {
      Return DllCall("libmysql.dll\mysql_list_tables", "Ptr", This.MYSQL
                   , "Ptr", (Like = "" ? 0 : This.UTF8(Like)), "UPtr")
   }
   ; ===================================================================================================================
   ; This function is used when you execute multiple statements specified as a single statement string, or when you
   ; execute CALL statements, which can return multiple result sets.
   ; Return values: TRUE (1) if more results exist. FALSE (0) if no more results exist.
   ; ===================================================================================================================
   More_Results() {
      Return DllCall("libmysql.dll\mysql_more_results", "Ptr", This.MYSQL, "Char")
   }
   ; ===================================================================================================================
   ; This function is used when you execute multiple statements specified as a single statement string, or when you use
   ; CALL statements to execute stored procedures, which can return multiple result sets.
   ; Return values:  0 : Successful and there are more results.
   ;                -1 : Successful and there are no more results.
   ;                >0 : An error occurred.
   ; ===================================================================================================================
   Next_Result() {
      Return DllCall("libmysql.dll\mysql_next_result", "Ptr", This.MYSQL, "Int")
   }
   ; ===================================================================================================================
   ; Returns the number of columns in a result set.
   ; Parameters:    MYSQL_RES - Pointer to a MYSQL_RES structure.
   ; Return values: An unsigned integer representing the number of columns in a result set.
   ; ===================================================================================================================
   Num_Fields(MYSQL_RES) {
      Return DllCall("libmysql.dll\mysql_num_fields", "Ptr", MYSQL_RES, "UInt")
   }
   ; ===================================================================================================================
   ; Returns the number of rows in a result set.
   ; Parameters:    MYSQL_RES - Pointer to a MYSQL_RES structure.
   ; Return values: An unsigned 64-bit integer representing the number of rows in a result set.
   ; ===================================================================================================================
   Num_Rows(MYSQL_RES) {
      Return DllCall("libmysql.dll\mysql_num_rows", "Ptr", MYSQL_RES, "UInt64")
   }
   ; ===================================================================================================================
   ; Can be used to set extra connect options and affect behavior for a connection.
   ; This function may be called multiple times to set several options.
   ; Parameters:    Option - The option that you want to set.
   ;                Arg    - The value for the option.
   ; Return values: Zero for success. Nonzero if you specify an unknown option.
   ; ===================================================================================================================
   Options(Option, Arg) {
      Static MySQL_Option := {MYSQL_OPT_CONNECT_TIMEOUT: 0, MYSQL_OPT_COMPRESS: 1, MYSQL_OPT_NAMED_PIPE: 2
                            , MYSQL_INIT_COMMAND: 3, MYSQL_READ_DEFAULT_FILE: 4, MYSQL_READ_DEFAULT_GROUP: 5
                            , MYSQL_SET_CHARSET_DIR: 6, MYSQL_SET_CHARSET_NAME: 7, MYSQL_OPT_LOCAL_INFILE: 8
                            , MYSQL_OPT_PROTOCOL: 9, MYSQL_SHARED_MEMORY_BASE_NAME: 10, MYSQL_OPT_READ_TIMEOUT: 11
                            , MYSQL_OPT_WRITE_TIMEOUT: 12, MYSQL_OPT_USE_RESULT: 13
                            , MYSQL_OPT_USE_REMOTE_CONNECTION: 14, MYSQL_OPT_USE_EMBEDDED_CONNECTION: 15
                            , MYSQL_OPT_GUESS_CONNECTION: 16, MYSQL_SET_CLIENT_IP: 17, MYSQL_SECURE_AUTH: 18
                            , MYSQL_REPORT_DATA_TRUNCATION: 19, MYSQL_OPT_RECONNECT: 20
                            , MYSQL_OPT_SSL_VERIFY_SERVER_CERT: 21, MYSQL_PLUGIN_DIR: 22, MYSQL_DEFAULT_AUTH: 23
                            , MYSQL_ENABLE_CLEARTEXT_PLUGIN: 24}
      If Option Is Not Integer
         Option := MYSQL_Option[Option]
      If Arg Is Integer
         Return DllCall("libmysql.dll\mysql_options", "Ptr", This.MYSQL, "Int", Option, "Int64P", Arg, "Int")
      Return DllCall("libmysql.dll\mysql_options", "Ptr", This.MYSQL, "Int", Option, "Ptr", This.UTF8(Arg), "Int")
   }
   ; ===================================================================================================================
   ; Checks whether the connection to the server is working.
   ; Return values: Zero if the connection to the server is active. Nonzero if an error occurred.
   ; ===================================================================================================================
   Ping() {
      Return DllCall("libmysql.dll\mysql_ping", "Ptr", This.MYSQL, "Int")
   }
   ; ===================================================================================================================
   ; Executes the SQL statement pointed to by the null-terminated string SQL.
   ; Parameters:    SQL   - SQL statement.
   ; Return values: Zero if the statement was successful. Nonzero if an error occurred.
   ; ===================================================================================================================
   Query(SQL) {
      Return DllCall("libmysql.dll\mysql_query", "Ptr", This.MYSQL, "Ptr", This.UTF8(SQL), "Int")
   }
   ; ===================================================================================================================
   ; Attempts to establish a connection to a MySQL database engine running on Host.
   ; Parameters:    Host   - A host name or an IP address.
   ;                User   - The user's MySQL login ID.
   ;                PassWd - The password for user.
   ;             Optional:
   ;                DB     - The database name.
   ;                Port   - The port number for the TCP/IP connection (Default: 3306)
   ;                Socket - A string specifying the socket or named pipe to use.
   ;                Flags  - Flags to enable certain features.
   ; Return values: A MYSQL* connection handle if the connection was successful, NULL if the connection was
   ;                unsuccessful. For a successful connection, the return value is the same as the handle passed to
   ;                mysql_real_connect() in the first parameter.
   ; ===================================================================================================================
   /*
   Query2Obj(SQL){
    This.Query(SQL)
    out := {}
    resultPtr := This.Store_Result()
    if resultPtr > 0
    {
        out.fieldCount := fieldCount := This.Field_Count()
        out.rowCount := rowCount := This.Num_Rows()
        out.data := []
        Loop
        {
            rowid := A_Index
            row := This.Fetch_Row(resultPtr)
            If (row = 0 || row == "")
                Break
            out.data[rowid] := []
            lengths := This.Fetch_Lengths(resultPtr)
            Loop % fieldCount
            {
                J := A_Index - 1
                If (Len := NumGet(Lengths + 0, 4 * J, "UInt"))
                    field := (StrGet(NumGet(row + 0, A_PtrSize * J, "UPtr"), Len, "UTF-8"))
                else
                    field=
                out.data[rowid].push(field)
            }
        }
    }
    return out
   }
   */

   Real_Connect(Host, User, PassWd, DB := "", Port := 3306, Socket := 0, Flags := 0) {
      If (DB = "")
         PtrDB := 0
      Else
         PtrDB := This.UTF8(DB)
      If !(MYSQL := DllCall("libmysql.dll\mysql_real_connect", "Ptr", This.MYSQL, "Ptr", This.UTF8(Host)
                          , "Ptr", This.UTF8(User), "Ptr", This.UTF8(PassWd), "Ptr", PtrDB
                          , "UInt", Port, "Ptr", This.UTF8(Socket), "Uint", Flags, "UPtr"))
         Return False
      Return MYSQL

   }
   ; ===================================================================================================================
   ; This function is used to create a legal SQL string that you can use in an SQL statement.
   ; The string in From is encoded to an escaped SQL string, taking into account the current character set of the
   ; connection.
   ; Parameters:    From   - Source string.
   ; Return values: Escaped string.
   ; ===================================================================================================================
   Real_Escape_String(ByRef From) {
      L := StrPut(From, "UTF-8") - 1
      VarSetCapacity(SI, L, 0)
      StrPut(From, &SI, "UTF-8")
      VarSetCapacity(SO, (L * 2) + 1, 0)
      N := DllCall("libmysql.dll\mysql_real_escape_string", "Ptr", This.MYSQL, "Ptr", &SO, "Ptr", &SI, "UInt", L, "UInt")
      Return StrGet(&SO, N, "UTF-8")
   }
   ; ===================================================================================================================
   ; Executes the SQL statement pointed to by SQL, a string Length bytes long.
   ; mysql_query() cannot be used for statements that contain binary data; you must use mysql_real_query() instead.
   ; All strings within the SQL statement have to be UTF-8.
   ; Parameters:    SQL    - SQL statement.
   ;                Length - Length of the statement in bytes.
   ; Return values: Zero if the statement was successful. Nonzero if an error occurred.
   ; ===================================================================================================================
   Real_Query(ByRef SQL, Length) {
      Return DllCall("libmysql.dll\mysql_real_query", "Ptr", This.MYSQL, "Ptr", &SQL, "UInt", Length, "Int")
   }
   ; ===================================================================================================================
   ; mysql_refresh() - not implemented <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
   ; mysql_reload()  - not implemented <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
   ; ===================================================================================================================
   ; ===================================================================================================================
   ; Rolls back the current transaction.
   ; Return values: Zero if successful. Nonzero if an error occurred.
   ; ===================================================================================================================
   Rollback() {
      Return DllCall("libmysql.dll\mysql_rollback", "Ptr", This.MYSQL, "Char")
   }
   ; ===================================================================================================================
   ; Sets the row cursor to an arbitrary row in a query result set.
   ; Parameters:    MYSQL_RES - Pointer to a MYSQL_RES structure
   ;                Offset    - The offset value is a row offset, typically a value returned from mysql_row_tell()
   ;                            or from mysql_row_seek(). This value is not a row number.
   ; Return values: The previous value of the row cursor.
   ; ===================================================================================================================
   Row_Seek(MYSQL_RES, Offset) {
      Return DllCall("libmysql.dll\mysql_row_seek", "Ptr", MYSQL_RES, "Ptr", Offset, "UPtr")
   }
   ; ===================================================================================================================
   ; Returns the current position of the row cursor for the last mysql_fetch_row(). This value can be used as an
   ; argument to mysql_row_seek().
   ; Parameters:    MYSQL_RES -  Pointer to a MYSQL_RES structure
   ; Return values: The current offset of the row cursor.
   ; ===================================================================================================================
   Row_Tell(MYSQL_RES) {
      Return DllCall("libmysql.dll\mysql_row_tell", "Ptr", MYSQL_RES, "UPtr")
   }
   ; ===================================================================================================================
   ; Causes the database specified by DB to become the default (current) database on the connection specified by mysql.
   ; In subsequent queries, this database is the default for table references that do not include an explicit database
   ; specifier.
   ; Parameters:    DB     - Database name.
   ; Return values: Zero if successful. Nonzero if an error occurred.
   ; ===================================================================================================================
   Select_DB(DB) {
      Return DllCall("libmysql.dll\mysql_select_db", "Ptr", This.MYSQL, "Ptr", This.UTF8(DB), "Int")
   }
   ; ===================================================================================================================
   ; This function is used to set the default character set for the current connection.
   ; Parameters:    CSName - Character set name.
   ; Return values: Zero if successful. Nonzero if an error occurred.
   ; ===================================================================================================================
   Set_Character_Set(CSName) {
      Return DllCall("libmysql.dll\mysql_set_character_set", "Ptr", This.MYSQL, "Ptr", This.UTF8(CSName), "Int")
   }
   ; ===================================================================================================================
   ; mysql_set_local_infile_default() - not implemented <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
   ; mysql_set_local_infile_handler() - not implemented <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
   ; ===================================================================================================================
   ; ===================================================================================================================
   ; Enables or disables an option for the connection.
   ; Parameters:    Option - MYSQL_OPTION_MULTI_STATEMENTS_ON  = 0
   ;                         MYSQL_OPTION_MULTI_STATEMENTS_OFF = 1
   ; Return values: Zero if successful. Nonzero if an error occurred.
   ; ===================================================================================================================
   Set_Server_Option(Option) {
      Return DllCall("libmysql.dll\mysql_set_server_option", "Ptr", This.MYSQL, "Int", Option, "Int")
   }
   ; ===================================================================================================================
   ; mysql_shutdown() - not implemented <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
   ; ===================================================================================================================
   ; ===================================================================================================================
   ; Returns a null-terminated string containing the SQLSTATE error code for the most recently executed SQL statement.
   ; The error code consists of five characters. '00000' means 鈥渘o error.鈥?
   ; Return values: A null-terminated character string containing the SQLSTATE error code.
   ; ===================================================================================================================
   SQLState() {
      Return ((P := DllCall("libmysql.dll\mysql_sqlstate", "Ptr", This.MYSQL, "UPtr")) ? StrGet(P, "UTF-8") : "")
   }
   ; ===================================================================================================================
   ; mysql_ssl_set() - not implemented <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
   ; ===================================================================================================================
   ; ===================================================================================================================
   ; Returns a character string containing information similar to that provided by the mysqladmin status command.
   ; Return values: A character string describing the server status. NULL if an error occurred.
   ; ===================================================================================================================
   Stat() {
      Return ((P := DllCall("libmysql.dll\mysql_stat", "Ptr", This.MYSQL, "UPtr")) ? StrGet(P, "UTF-8") : "")
   }
   ; ===================================================================================================================
   ; After invoking mysql_query() or mysql_real_query(), you must call mysql_store_result() or mysql_use_result() for
   ; every statement that successfully produces a result set (SELECT, SHOW, DESCRIBE, EXPLAIN, CHECK TABLE, and so
   ; forth).
   ; Return values: A pointer to a MYSQL_RES result structure with the results. NULL (0) if an error occurred.
   ; ===================================================================================================================
   Store_Result() {
      Return DllCall("libmysql.dll\mysql_store_result", "Ptr", This.MYSQL, "UPtr")
   }
   ; ===================================================================================================================
   ; Returns the thread ID of the current connection.
   ; Return values: The thread ID of the current connection.
   ; ===================================================================================================================
   Thread_ID() {
      Return DllCall("libmysql.dll\mysql_thread_id", "Ptr", This.MYSQL, "UInt")
   }
   ; ===================================================================================================================
   ; After invoking mysql_query() or mysql_real_query(), you must call mysql_store_result() or mysql_use_result() for
   ; every statement that successfully produces a result set (SELECT, SHOW, DESCRIBE, EXPLAIN, CHECK TABLE, and so
   ; forth).
   ; Return values: A pointer to a MYSQL_RES result structure with the results. NULL (0) if an error occurred.
   ; ===================================================================================================================
   Use_Result() {
      Return DllCall("libmysql.dll\mysql_use_result", "Ptr", This.MYSQL, "UPtr")
   }
   ; ===================================================================================================================
   ; Returns the number of errors, warnings, and notes generated during execution of the previous SQL statement.
   ; Return values: The warning count.
   ; ===================================================================================================================
   Warning_Count() {
      Return DllCall("libmysql.dll\mysql_warning_count", "Ptr", This.MYSQL, "UInt")
   }
}


Elastix 2.5的系统是Centos 5.9,Asterisk 11。在测试dialpan拨号方案使用odbc mysql的时候报错驱动/usr/lib64/libmyodbc3_r.so找不到,经验证是系统的mysql-connector-odbc没有安装。

在通过yum安装的时候又发现源已经停止服务了,无法下载,找到一个国外源fq下载完,在另外一台机子上则是选择本地安装yum包,下载地址:

https://centos.pkgs.org/5/centos-x86_64/mysql-connector-odbc-3.51.26r1127-2.el5.x86_64.rpm.html  (x64)

https://centos.pkgs.org/5/centos-i386/mysql-connector-odbc-3.51.26r1127-2.el5.i386.rpm.html (x86)

下载完后可以放到当前目录 shell执行:

yum -y localinstall mysql-connector-odbc-3.51.26r1127-2.el5.x86_64.rpm

安装完成后还需配置/etc/odbc.ini:

[MYSQL-asteriskcdrdb]
Description = MySQL connection to 'asterisk' database
Driver = MySQL
Database = asteriskcdrdb
Server = localhost
Port = 3306
Socket = /var/lib/mysql/mysql.sock
User = root
Password = MyPass
Option = 3

配置完成后可以在shell中测试:

[root@Elastix ~]# isql -v MYSQL-asteriskcdrdb
+---------------------------------------+
| Connected!                            |
|                                       |
| sql-statement                         |
| help [tablename]                      |
| quit                                  |
|                                       |
+---------------------------------------+
SQL> show tables;
+-----------------------------------------------------------------+
| Tables_in_asteriskcdrdb                                         |
+-----------------------------------------------------------------+
| cdr                                                             |
+-----------------------------------------------------------------+
SQLRowCount returns 1
1 rows fetched

这就算完成了一半,还需在/etc/asterisk/res_odbc.conf中配置dsn:

[asteriskcdrdb]
enabled=>yes
dsn=>MySQL-asteriskcdrdb
pooling=>no
limit=>1
pre-connect=>yes
share_connections => yes
isolation => repeatable_read
forcecommit => yes

在/etc/asterisk/func_odbc.conf中配置自定义函数(此处dsn指res_odbc.conf中的[name]):

[SQL]
dsn=asteriskcdrdb
readsql=${ARG1}
synopsis=ODBC_SQL(sql)

具体配置说明详见:https://wiki.asterisk.org/wiki/display/AST/Getting+Asterisk+Connected+to+MySQL+via+ODBC

http://www.asteriskdocs.org/en/3rd_Edition/asterisk-book-html-chunk/getting_funky.html

配置完后注意在Asterisk CLI中执行reload或者shell执行:

asterisk -x reload

最后就可以在dialpan中测试使用了,如下面的例子(/etc/asterisk/extensions.conf)拨打876在asterisk日志中输出结果:

[from-internal]
exten => 876,1,Answer
exten => 876,n,Noop(${ODBC_SQL("select now()")})
exten => 876,n,Noop(${ODBC_SQL("select top 1 uniquid from cdr order by calldate desc")})
exten => 876,n,Background(star)
exten => 876,n,Wait(60)
include => from-internal-noxfer
include => from-internal-xfer
include => bad-number ; auto-generated



友情链接:Autohotkey中文帮助Autohotkey官网Autohotkey中文网联系作者免GooglePlay APK下载

 主题设计 • skyfrit.com  Thinkai's Blog | 保留所有权利

40 queries in 1.499 seconds |