Sweep LAN SQLServer

xiaoxiao2021-03-06  37

Use: Private Void Button1_Click_1 (Object Sender, System.eventargs E) {String [] Servers = DBGREP.SQLLOCATOR.GETSERVERS (); foreach (string s in servers) {this.listbox1.items.add (s);}}

Class code Using system; use system.text; using system.windows.forms; using system.Runtime.interopservices;

namespace DBGrep {public class SqlLocator {[DllImport ( "odbc32.dll")] private static extern short SQLAllocHandle (short hType, IntPtr inputHandle, out IntPtr outputHandle); [DllImport ( "odbc32.dll")] private static extern short SQLSetEnvAttr ( IntPtr henv, int attribute, IntPtr valuePtr, int strLength); [DllImport ( "odbc32.dll")] private static extern short SQLFreeHandle (short hType, IntPtr handle); [DllImport ( "odbc32.dll", CharSet = CharSet.Ansi ] Private Static Extern Short SqlBrowSeconnect (INTPTR HCONN, STRINGBUILDER Instring, Short InstringLength, StringBuilder Outstring, Short OutstringLength, Out Short Outlength ";

private const short SQL_HANDLE_ENV = 1; private const short SQL_HANDLE_DBC = 2; private const int SQL_ATTR_ODBC_VERSION = 200; private const int SQL_OV_ODBC3 = 3; private const short SQL_SUCCESS = 0; private const short SQL_NEED_DATA = 99; private const short DEFAULT_RESULT_SIZE = 1024; private Const string sql_driver_str = "driver = SQL Server"; private sqllocator () {}

public static string [] GetServers () {string [] retval = null; string txt = string.Empty; IntPtr henv = IntPtr.Zero; IntPtr hconn = IntPtr.Zero; StringBuilder inString = new StringBuilder (SQL_DRIVER_STR); StringBuilder outString = new StringBuilder; Short InstringLength = (Short) Instring.Length; Short lenneeded = 0;

try {if (SQL_SUCCESS == SQLAllocHandle (SQL_HANDLE_ENV, henv, out henv)) {if (SQL_SUCCESS == SQLSetEnvAttr (henv, SQL_ATTR_ODBC_VERSION, (IntPtr) SQL_OV_ODBC3,0)) {if (SQL_SUCCESS == SQLAllocHandle (SQL_HANDLE_DBC, henv, out hconn)) {if (SQL_NEED_DATA == SQLBrowseConnect (hconn, inString, inStringLength, outString, DEFAULT_RESULT_SIZE, out lenNeeded)) {if (DEFAULT_RESULT_SIZE 0) && (LEN> 0)) {txt = txt.substring (start, len);} else {txt = string.emp Ty;}}}}}} catch (Exception ex) {// throw away any error}} (ex. subssage, "acquire sql servier list error"); # m d Endif txt = string.empty;} finally {if (hconn! = INTPTR.ZERO) {SQLFreeHandle (SQL_HANDLE_DBC, HCONN);} if (henv! = INTPTR.ZERO) {SQLFreeHandle (SQL_HANDE_ENV, HCONN);}}} f .Length> 0) {RetVal = txt.split (",". Tochararray ());}}}}}}

转载请注明原文地址:https://www.9cbs.com/read-118382.html

New Post(0)