SQLDMO For C#

本文介绍如何使用SQLDMO列举网络中的SQL服务器、连接服务器获取数据库列表,并进一步获取表、存储过程及视图等对象。通过示例代码展示了简单实用的操作步骤。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

http://www.csharphelp.com/archives2/archive342.html

All of the operations performed in the example use one or more of the following objects:

    • SQLDMO.Application
    • SQLDMO.SQLServer
    • SQLDMO.Database
    • SQLDMO.NameList

There are a multitude of objects available for actions such as backups and restores, but for the purpose of this article I decided to keep it simple to ease you into the world of SQLDMO.

Listing the available SQL Servers on your network is quite simple.  First you need a references SQLDMO.Application object.  Next you set an instance of SQLDMO.NameList to the return value of the SQLDMO.Application.ListAvailableSQLServers() method.  The SQLDMO.NameList if a COM collection of the server names.  

Keep in mind, calling COM objects is a little funky until you get used to it, but the conventions are similar with all of them.  Here is example code which fills a combo box name cboServers with a list of all available SQL Servers on the local network:

//get all available SQL Servers    
SQLDMO.Application sqlApp = new SQLDMO.ApplicationClass();
SQLDMO.NameList sqlServers = sqlApp.ListAvailableSQLServers();
for(int i=0;i<sqlServers.Count;i++)
{
    object srv = sqlServers.Item(i + 1);
    if(srv != null)
    {
        this.cboServers.Items.Add(srv);                        
    }
}
if(this.cboServers.Items.Count > 0)
    this.cboServers.SelectedIndex = 0;
else
    this.cboServers.Text = "<No available SQL Servers>";

As you can see, this is quite simple.  Just remember that COM collections start at an index of 1, not 0. 

Connecting to a server and getting a list of databases is also fairly simple.  The following code will take the chosen SQL Server in the combo box, connect to it (with a user name and password in 2 text boxes), and then poulates another combo box with a list of databases on the server.

//get all available databases from an SQL Server
SQLDMO.Application sqlApp = new SQLDMO.ApplicationClass();
SQLDMO.SQLServer srv = new SQLDMO.SQLServerClass();                
srv.Connect(this.cboServers.SelectedItem.ToString(),this.txtUser.Text,this.txtPassword.Text);
foreach(SQLDMO.Database db in srv.Databases)
{
    if(db.Name!=null)
        this.cboDatabase.Items.Add(db.Name);
}

Getting a list of objects by type is also a breeze with this library.  Again, you make a connection to the database, and then you loop through the object collection. 

//Get all Stored procedures - tables are in the Tables collection, views are in the Views collection
SQLDMO.SQLServer srv = new SQLDMO.SQLServerClass();                
srv.Connect(this.cboServers.SelectedItem.ToString(),this.txtUser.Text,this.txtPassword.Text);
for(int i=0;i<srv.Databases.Count;i++)
{
    if(srv.Databases.Item(i+1,"dbo").Name == this.cboDatabase.SelectedItem.ToString())
    {
        SQLDMO._Database db= srv.Databases.Item(i+1,"dbo");
        this.lstObjects.Items.Clear();
        for(int j=0;j<db.StoredProcedures.Count;j++)
        {
            this.lstObjects.Items.Add(db.StoredProcedures.Item(j+1,"dbo").Name);
        } 
        break;
    }
}

Well folks, that is it for my SQLDMO beginners' tutorial.  Please download the sample code and app to see it in action.  As you can see, this is a much easier alternative when SQL information or control is needed.  Happy coding!!!

=================
Form1.cs
using System;
using System.Drawing;
using System.Collections;
using System.ComponentModel;
using System.Windows.Forms;
using System.Data;


namespace SQLDMOSample
{
    /// <summary>
    /// Summary description for Form1.
    /// </summary>
    ///


    public class Form1 : System.Windows.Forms.Form
    {
        private SQLDMO.Application sqlApp = new SQLDMO.ApplicationClass();
        SQLDMO.NameList sqlServers=null;
        private System.Windows.Forms.ComboBox cboServers;
        private System.Windows.Forms.Label label1;
        private System.Windows.Forms.Label label2;
        private System.Windows.Forms.TextBox txtUser;
        private System.Windows.Forms.Label label3;
        private System.Windows.Forms.TextBox txtPassword;
        private System.Windows.Forms.ListBox lstObjects;
        private System.Windows.Forms.ComboBox cboDatabase;
        private System.Windows.Forms.Label label4;
        private System.Windows.Forms.LinkLabel linkLabel2;
        private System.Windows.Forms.GroupBox groupBox1;
        private System.Windows.Forms.LinkLabel linkLabel1;
        private System.Windows.Forms.LinkLabel linkLabel3;
        private System.Windows.Forms.LinkLabel linkLabel4;
        /// <summary>
        /// Required designer variable.
        /// </summary>
        private System.ComponentModel.Container components = null;

        public Form1()
        {
            //
            // Required for Windows Form Designer support
            //
            InitializeComponent();

            //
            // TODO: Add any constructor code after InitializeComponent call
            //
        }

        /// <summary>
        /// Clean up any resources being used.
        /// </summary>
        protected override void Dispose( bool disposing )
        {
            if( disposing )
            {
                if (components != null)
                {
                    components.Dispose();
                }
            }
            base.Dispose( disposing );
        }

        #region Windows Form Designer generated code
        /// <summary>
        /// Required method for Designer support - do not modify
        /// the contents of this method with the code editor.
        /// </summary>
        private void InitializeComponent()
        {
            this.cboServers = new System.Windows.Forms.ComboBox();
            this.label1 = new System.Windows.Forms.Label();
            this.label2 = new System.Windows.Forms.Label();
            this.txtUser = new System.Windows.Forms.TextBox();
            this.label3 = new System.Windows.Forms.Label();
            this.txtPassword = new System.Windows.Forms.TextBox();
            this.lstObjects = new System.Windows.Forms.ListBox();
            this.cboDatabase = new System.Windows.Forms.ComboBox();
            this.label4 = new System.Windows.Forms.Label();
            this.linkLabel2 = new System.Windows.Forms.LinkLabel();
            this.groupBox1 = new System.Windows.Forms.GroupBox();
            this.linkLabel1 = new System.Windows.Forms.LinkLabel();
            this.linkLabel3 = new System.Windows.Forms.LinkLabel();
            this.linkLabel4 = new System.Windows.Forms.LinkLabel();
            this.groupBox1.SuspendLayout();
            this.SuspendLayout();
            //
            // cboServers
            //
            this.cboServers.Location = new System.Drawing.Point(8, 24);
            this.cboServers.Name = "cboServers";
            this.cboServers.Size = new System.Drawing.Size(240, 21);
            this.cboServers.TabIndex = 0;
            this.cboServers.SelectedIndexChanged += new System.EventHandler(this.cboServers_SelectedIndexChanged);
            //
            // label1
            //
            this.label1.Location = new System.Drawing.Point(8, 8);
            this.label1.Name = "label1";
            this.label1.Size = new System.Drawing.Size(240, 16);
            this.label1.TabIndex = 1;
            this.label1.Text = "SQL Servers";
            //
            // label2
            //
            this.label2.Location = new System.Drawing.Point(8, 48);
            this.label2.Name = "label2";
            this.label2.Size = new System.Drawing.Size(120, 16);
            this.label2.TabIndex = 2;
            this.label2.Text = "User Name";
            //
            // txtUser
            //
            this.txtUser.Location = new System.Drawing.Point(8, 64);
            this.txtUser.Name = "txtUser";
            this.txtUser.Size = new System.Drawing.Size(240, 20);
            this.txtUser.TabIndex = 3;
            this.txtUser.Text = "sa";
            //
            // label3
            //
            this.label3.Location = new System.Drawing.Point(8, 88);
            this.label3.Name = "label3";
            this.label3.Size = new System.Drawing.Size(88, 16);
            this.label3.TabIndex = 4;
            this.label3.Text = "Password";
            //
            // txtPassword
            //
            this.txtPassword.Location = new System.Drawing.Point(8, 104);
            this.txtPassword.Name = "txtPassword";
            this.txtPassword.Size = new System.Drawing.Size(240, 20);
            this.txtPassword.TabIndex = 5;
            this.txtPassword.Text = "";
            //
            // lstObjects
            //
            this.lstObjects.HorizontalScrollbar = true;
            this.lstObjects.Location = new System.Drawing.Point(256, 8);
            this.lstObjects.Name = "lstObjects";
            this.lstObjects.Size = new System.Drawing.Size(240, 290);
            this.lstObjects.TabIndex = 6;
            //
            // cboDatabase
            //
            this.cboDatabase.Enabled = false;
            this.cboDatabase.Location = new System.Drawing.Point(8, 152);
            this.cboDatabase.Name = "cboDatabase";
            this.cboDatabase.Size = new System.Drawing.Size(240, 21);
            this.cboDatabase.TabIndex = 8;
            this.cboDatabase.SelectedIndexChanged += new System.EventHandler(this.cboDatabase_SelectedIndexChanged);
            //
            // label4
            //
            this.label4.Location = new System.Drawing.Point(8, 136);
            this.label4.Name = "label4";
            this.label4.Size = new System.Drawing.Size(88, 16);
            this.label4.TabIndex = 9;
            this.label4.Text = "Databases";
            //
            // linkLabel2
            //
            this.linkLabel2.Location = new System.Drawing.Point(168, 136);
            this.linkLabel2.Name = "linkLabel2";
            this.linkLabel2.Size = new System.Drawing.Size(80, 16);
            this.linkLabel2.TabIndex = 10;
            this.linkLabel2.TabStop = true;
            this.linkLabel2.Text = "Connect";
            this.linkLabel2.TextAlign = System.Drawing.ContentAlignment.TopRight;
            this.linkLabel2.LinkClicked += new System.Windows.Forms.LinkLabelLinkClickedEventHandler(this.linkLabel2_LinkClicked);
            //
            // groupBox1
            //
            this.groupBox1.Controls.AddRange(new System.Windows.Forms.Control[] {
                                                                                    this.linkLabel4,
                                                                                    this.linkLabel3,
                                                                                    this.linkLabel1});
            this.groupBox1.Enabled = false;
            this.groupBox1.Location = new System.Drawing.Point(8, 176);
            this.groupBox1.Name = "groupBox1";
            this.groupBox1.Size = new System.Drawing.Size(240, 120);
            this.groupBox1.TabIndex = 11;
            this.groupBox1.TabStop = false;
            //
            // linkLabel1
            //
            this.linkLabel1.Location = new System.Drawing.Point(152, 16);
            this.linkLabel1.Name = "linkLabel1";
            this.linkLabel1.Size = new System.Drawing.Size(72, 16);
            this.linkLabel1.TabIndex = 0;
            this.linkLabel1.TabStop = true;
            this.linkLabel1.Text = "Get Tables";
            this.linkLabel1.TextAlign = System.Drawing.ContentAlignment.TopRight;
            this.linkLabel1.LinkClicked += new System.Windows.Forms.LinkLabelLinkClickedEventHandler(this.linkLabel1_LinkClicked);
            //
            // linkLabel3
            //
            this.linkLabel3.Location = new System.Drawing.Point(104, 40);
            this.linkLabel3.Name = "linkLabel3";
            this.linkLabel3.Size = new System.Drawing.Size(120, 16);
            this.linkLabel3.TabIndex = 1;
            this.linkLabel3.TabStop = true;
            this.linkLabel3.Text = "Get Stored Procedures";
            this.linkLabel3.TextAlign = System.Drawing.ContentAlignment.TopRight;
            this.linkLabel3.LinkClicked += new System.Windows.Forms.LinkLabelLinkClickedEventHandler(this.linkLabel3_LinkClicked);
            //
            // linkLabel4
            //
            this.linkLabel4.Location = new System.Drawing.Point(112, 64);
            this.linkLabel4.Name = "linkLabel4";
            this.linkLabel4.Size = new System.Drawing.Size(112, 16);
            this.linkLabel4.TabIndex = 2;
            this.linkLabel4.TabStop = true;
            this.linkLabel4.Text = "Views";
            this.linkLabel4.TextAlign = System.Drawing.ContentAlignment.TopRight;
            this.linkLabel4.LinkClicked += new System.Windows.Forms.LinkLabelLinkClickedEventHandler(this.linkLabel4_LinkClicked);
            //
            // Form1
            //
            this.AutoScaleBaseSize = new System.Drawing.Size(5, 13);
            this.ClientSize = new System.Drawing.Size(504, 301);
            this.Controls.AddRange(new System.Windows.Forms.Control[] {
                                                                          this.groupBox1,
                                                                          this.linkLabel2,
                                                                          this.label4,
                                                                          this.cboDatabase,
                                                                          this.lstObjects,
                                                                          this.txtPassword,
                                                                          this.label3,
                                                                          this.txtUser,
                                                                          this.label2,
                                                                          this.label1,
                                                                          this.cboServers});
            this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedSingle;
            this.MaximizeBox = false;
            this.Name = "Form1";
            this.StartPosition = System.Windows.Forms.FormStartPosition.CenterScreen;
            this.Text = "SQLDMO Example";
            this.Load += new System.EventHandler(this.Form1_Load);
            this.groupBox1.ResumeLayout(false);
            this.ResumeLayout(false);

        }
        #endregion

        /// <summary>
        /// The main entry point for the application.
        /// </summary>
        [STAThread]
        static void Main()
        {
            Application.Run(new Form1());
        }

        private void cboServers_SelectedIndexChanged(object sender, System.EventArgs e)
        {
            this.cboDatabase.Items.Clear();
            this.cboDatabase.Enabled = false;
            this.groupBox1.Enabled = false;
            this.lstObjects.Items.Clear();
        }

        private void Form1_Load(object sender, System.EventArgs e)
        {
            try
            {
                //get all available SQL Servers               
                sqlServers = sqlApp.ListAvailableSQLServers();
                for(int i=0;i<sqlServers.Count;i++)
                {
                    object srv = sqlServers.Item( i + 1);
                    if(srv != null)
                    {
                        this.cboServers.Items.Add(srv);                       
                    }
                }
                if(this.cboServers.Items.Count > 0)
                    this.cboServers.SelectedIndex = 0;
                else
                    this.cboServers.Text = "<No available SQL Servers>";

            }
            catch(Exception err)
            {
                MessageBox.Show(err.Message,"Error");
            }
        }

        //Get Tables
        private void linkLabel2_LinkClicked(object sender, System.Windows.Forms.LinkLabelLinkClickedEventArgs e)
        {
            try
            {
                this.Cursor = Cursors.WaitCursor;
                this.lstObjects.Items.Clear();
                this.cboDatabase.Items.Clear();               
           
                SQLDMO.SQLServer srv = new SQLDMO.SQLServerClass();               
                srv.Connect(this.cboServers.SelectedItem.ToString(),this.txtUser.Text,this.txtPassword.Text);

                foreach(SQLDMO.Database db in srv.Databases)
                {
                    if(db.Name!=null)
                        this.cboDatabase.Items.Add(db.Name);
                }
                this.cboDatabase.Sorted = true;
                if(this.cboDatabase.Items.Count >0)
                {
                    this.cboDatabase.SelectedIndex = 0;
                    this.cboDatabase.Enabled = true;
                    this.groupBox1.Enabled = true;
                }
                else
                {
                    this.groupBox1.Enabled = false;
                    this.cboDatabase.Enabled = false;
                    this.cboDatabase.Text = "<No databases found>";
                }
                this.Cursor = Cursors.Default;
            }
            catch(Exception err)
            {
                this.Cursor = Cursors.Default;
                MessageBox.Show(err.Message,"Error");
            }
        }
       

        //Get stored procedures
        private void linkLabel1_LinkClicked(object sender, System.Windows.Forms.LinkLabelLinkClickedEventArgs e)
        {
            this.Cursor = Cursors.WaitCursor;
            SQLDMO.SQLServer srv = new SQLDMO.SQLServerClass();               
            srv.Connect(this.cboServers.SelectedItem.ToString(),this.txtUser.Text,this.txtPassword.Text);
            for(int i=0;i<srv.Databases.Count;i++)
            {
                if(srv.Databases.Item(i+1,"dbo").Name == this.cboDatabase.SelectedItem.ToString())
                {
                    SQLDMO._Database db= srv.Databases.Item(i+1,"dbo");
                    this.lstObjects.Items.Clear();
                    for(int j=0;j<db.Tables.Count;j++)
                    {
                        this.lstObjects.Items.Add(db.Tables.Item(j+1,"dbo").Name);
                    }
                    this.Cursor = Cursors.Default;
                    return;
                }
            }
            this.Cursor = Cursors.Default;
        }
       
        // Get Views
        private void linkLabel3_LinkClicked(object sender, System.Windows.Forms.LinkLabelLinkClickedEventArgs e)
        {
            this.Cursor = Cursors.WaitCursor;
            SQLDMO.SQLServer srv = new SQLDMO.SQLServerClass();               
            srv.Connect(this.cboServers.SelectedItem.ToString(),this.txtUser.Text,this.txtPassword.Text);
            for(int i=0;i<srv.Databases.Count;i++)
            {
                if(srv.Databases.Item(i+1,"dbo").Name == this.cboDatabase.SelectedItem.ToString())
                {
                    SQLDMO._Database db= srv.Databases.Item(i+1,"dbo");
                    this.lstObjects.Items.Clear();
                   
                    for(int j=0;j<db.StoredProcedures.Count;j++)
                    {
                        this.lstObjects.Items.Add(db.StoredProcedures.Item(j+1,"dbo").Name);
                    }
                    this.Cursor = Cursors.Default;
                    return;
                }
            }
            this.Cursor = Cursors.Default;
        }

        private void linkLabel4_LinkClicked(object sender, System.Windows.Forms.LinkLabelLinkClickedEventArgs e)
        {
            this.Cursor = Cursors.WaitCursor;
            SQLDMO.SQLServer srv = new SQLDMO.SQLServerClass();               
            srv.Connect(this.cboServers.SelectedText,this.txtUser.Text,this.txtPassword.Text);
            for(int i=0;i<srv.Databases.Count;i++)
            {
                if(srv.Databases.Item(i+1,"dbo").Name == this.cboDatabase.SelectedItem.ToString())
                {
                    SQLDMO._Database db= srv.Databases.Item(i+1,"dbo");
                    this.lstObjects.Items.Clear();
                    for(int j=0;j<db.Views.Count;j++)
                    {
                        this.lstObjects.Items.Add(db.Views.Item(j+1,"dbo").Name);
                    }
                    this.Cursor = Cursors.Default;
                    return;
                }
            }
            this.Cursor = Cursors.Default;
        }

        private void cboDatabase_SelectedIndexChanged(object sender, System.EventArgs e)
        {
            this.lstObjects.Items.Clear();
        }

       
    }
}
======================

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值