using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Data.SqlClient;
using System.Xml;
namespace test
{
public class SqlLocator
{
[System.Runtime.InteropServices.DllImport("odbc32.dll")]
private static extern short SQLAllocHandle(short hType, IntPtr inputHandle, out IntPtr outputHandle);
[System.Runtime.InteropServices.DllImport("odbc32.dll")]
private static extern short SQLSetEnvAttr(IntPtr henv, int attribute, IntPtr valuePtr, int strLength);
[System.Runtime.InteropServices.DllImport("odbc32.dll")]
private static extern short SQLFreeHandle(short hType, IntPtr handle);
[System.Runtime.InteropServices.DllImport("odbc32.dll", CharSet = System.Runtime.InteropServices.CharSet.Ansi)]
private static extern short SQLBrowseConnect(IntPtr hconn, System.Text.StringBuilder inString,
short inStringLength, System.Text.StringBuilder outString, short outStringLength,
out short outLengthNeeded);
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() { }
//查找所有server
public static string[] GetServers()
{
string list = string.Empty;
IntPtr henv = IntPtr.Zero;
IntPtr hconn = IntPtr.Zero;
System.Text.StringBuilder inString = new System.Text.StringBuilder(SQL_DRIVER_STR);
System.Text.StringBuilder outString = new System.Text.StringBuilder(DEFAULT_RESULT_SIZE);
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 < lenNeeded)
{
outString.Capacity = lenNeeded;
if (SQL_NEED_DATA != SQLBrowseConnect(hconn, inString, inStringLength, outString,
lenNeeded, out lenNeeded))
{
throw new ApplicationException("Unabled to aquire SQL Servers from ODBC driver.");
}
}
list = outString.ToString();
int start = list.IndexOf("{") + 1;
int len = list.IndexOf("}") - start;
if ((start > 0) && (len > 0))
{
list = list.Substring(start, len);
}
else
{
list = string.Empty;
}
}
}
}
}
}
catch
{
list = string.Empty;
}
finally
{
if (hconn != IntPtr.Zero)
{
SQLFreeHandle(SQL_HANDLE_DBC, hconn);
}
if (henv != IntPtr.Zero)
{
SQLFreeHandle(SQL_HANDLE_ENV, hconn);
}
}
string[] array = null;
if (list.Length > 0)
{
array = list.Split(',');
}
return array;
}
}
public partial class GetIP : Form
{
private Button reloadButton = new Button();
private Button submitButton = new Button();
private Label l1 = new Label();
private Label l2 = new Label();
private Label l3 = new Label();
private ComboBox textbox1 = new ComboBox();
private TextBox textbox2 = new TextBox();
private TextBox textbox3 = new TextBox();
private string connstr;
[STAThread]
static void Main()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new GetIP());
}
public GetIP()
{
reloadButton.Text = "测试连接";
submitButton.Text = "保存配置";
l1.Text = "服务器的IP:";
l2.Text = "用户名:";
l3.Text = "密码:";
reloadButton.Click += new System.EventHandler(reloadButton_Click);
submitButton.Click += new System.EventHandler(submitButton_Click);
FlowLayoutPanel panel = new FlowLayoutPanel();
panel.Dock = DockStyle.Top;
panel.AutoSize = true;
textbox1.DataSource = SqlLocator.GetServers();
panel.Controls.AddRange(new Control[] { l1, textbox1 });
panel.Controls.AddRange(new Control[] { l2, textbox2 });
panel.Controls.AddRange(new Control[] { l3, textbox3 });
panel.Controls.AddRange(new Control[] { reloadButton, submitButton });
this.Controls.Add(panel);
this.Load += new System.EventHandler(Form1_Load);
this.Text = "AutoGetIp and Connect MSSQL";
}
private void Form1_Load(object sender, System.EventArgs e)
{
submitButton.Enabled = true;
}
private void reloadButton_Click(object sender, System.EventArgs e)
{
try
{
connstr = "Data Source=" + textbox1.Text + ";Initial Catalog=eslx;User ID=" + textbox2.Text + ";Password=" + textbox3.Text;
SqlConnection conn = new SqlConnection(connstr);
conn.Open();
conn.Close();
MessageBox.Show("连接成功!!!");
submitButton.Enabled = true;//连接成功才能保存
}
catch
{
MessageBox.Show("连接无效!!!");
}
}
private void submitButton_Click(object sender, System.EventArgs e)
{
XmlDocument doc = new XmlDocument();
string p = "eslx.exe.config";//bin/debug/
doc.Load(p);
XmlNode node = doc.SelectSingleNode(@"//add[@name='eslx.Properties.Settings.eslxConnectionString']");
XmlElement ele = (XmlElement)node;
ele.SetAttribute("connectionString", connstr);
doc.Save(p);
MessageBox.Show("保存成功,现在登录!!");
}
}
}
配置文件:eslx.exe.config
<connectionStrings>
<add name="eslx.Properties.Settings.eslxConnectionString" connectionString="Data Source=.;Initial Catalog=eslx;User ID=sa;Password=lyk" providerName="System.Data.SqlClient" />
</connectionStrings>
感谢 ncjcz 提供的核心代码
http://topic.csdn.net/u/20091029/09/faa8d2af-6e04-442c-81a0-7e616050ed36.html
后面还一个更简单的方法 :
List<string> list=new List<string> ();
foreach (DataRow DR in System.Data.Sql.SqlDataSourceEnumerator.Instance.GetDataSources().Rows)
{
list.Add(DR["ServerName"].ToString());
}
textbox1.DataSource = list;//简单好记