C#用SQLDMO操作数据库
sqldmo.dll是随sql server2000一起发布的。sqldmo.dll自身是一个com对象
sqldmo(sql distributed management objects,sql分布式管理对象)封装 microsoft sql server 2000
数据库中的对象。sql-dmo 允许用支持
自动化或 com 的语言编写
应用程序,以管理 sql server 安装的所有部分。sql-dmo 是 sql server 2000 中的 sql server 企业管理器所使用的
应用程序接口 (api);因此使用 sql-dmo 的
应用程序可以执行 sql server 企业管理器执行的所有功能。
------
sqlserver的大致关系:
application-->sqlserver-->database
------
实例sqldmo,主要用到的是其中的以下几个类:
sqldmo.application(使用 sqldmo.applicationclass创建)、
sqldmo.sqlserver(使用sqldmo.sqlserverclass创建,主要用到它的connect来连接
数据库服务器)、
sqldmo.namelist(可以通过它和application获取服务器集合,其它的请看其api)
sqldmo.database(可以通过它和sqlserver.databases获取
数据库集合)
示例一:获取局域网内sql服务器列表
主要用到application的listavaiablesqlservers来获取namelist,

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

示例二:获取某个服务器下的
数据库列表:
主要用到sqlserver以及其属性databases

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

下面是SMO的基本操作
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.SqlServer.Management.Common;
using Microsoft.SqlServer.Management.Smo;
using Microsoft.SqlServer.Management;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
//建立数据库实例连接
Server s = new Server("POOFLY-PC");
ServerConnection sc = s.ConnectionContext;
sc.LoginSecure = false;
sc.Login = "sa";
sc.Password = "123456";
sc.Connect();
//输出数据库数目和第一个数据库名
Console.WriteLine("DatabaseCount:" + s.Databases.Count);
Console.WriteLine(s.Databases[0].Name);
//创建数据库
Database db = new Database(s, "newdb");
db.Create();
//建表Tb
Table tb = new Table(db, "NewTableName");
Column c = new Column(tb, "CustomerID");
c.Identity = true;
c.IdentitySeed = 1;
c.DataType = DataType.Int;
c.Nullable = false;
tb.Columns.Add(c);
c = new Column(tb, "CustomerName");
c.DataType = DataType.VarChar(20);
c.Nullable = true;
tb.Columns.Add(c);
tb.Create();
//创建存储过程
StoredProcedure sp = new StoredProcedure(db, "sptest");
StoredProcedureParameter pa1 = new StoredProcedureParameter(sp, "@pa1", DataType.Int);
sp.TextMode = false;
sp.Parameters.Add(pa1);
sp.TextBody = "select * from NewTableName where CustomerID=@pa1";
sp.Create();
//执行存储过程
db.ExecuteNonQuery("sptest 1");
}
}
}