浅析SQL Server 2005数据库中的SMO

来源:互联网 发布:党员干部网络八不准 编辑:程序博客网 时间:2024/06/05 02:25
 对数据库连接的方式,具体的根据下面的程序,大家会有一个比较清晰的认识:3、连接数据库,获取数据库对象的URN,如,表,数据库,存储过程,程序集等using microsoft.SqlServer.Management.Common;

  1、数据库的连接与关闭

  //方式一

  ServerConnection conn = new ServerConnection(”计算机的名字”);

  Server canopus5 = new Server(conn);

  ServerConnection conn2 = canopus5.ConnectionContext;//获取这个连接的引用

  //方式2

  Server Server = new Server(”localhost”);

  Server.ConnectionContext.Connect();

  Server.Initialize(false);

  //表示不加载数据库服务器的属性,如果是true,则强制加

  载属性

  Console.WriteLine(Server.State.ToString());

  Console.WriteLine(ServerConnection.ProcessID);//52

  Console.ReadLine();

  //关闭数据库

  Server.ConnectionContext.SQLConnectionObject.Close();

  对数据库连接的方式,具体的根据下面的程序,大家会有一个比较清晰的认识:

  //首先给大家介绍的默认连接的形式

  ServerConnection ServerConnection = new ServerConnection();

  ServerConnection.Connect();

  //数据库,我们采用的混合模式

  Console.WriteLine(ServerConnection.ConnectionString.ToString());

  //默认是使用

  Windows的认证模式,

  //所以下面的属性是空的

  Console.WriteLine(ServerConnection.ConnectAsUserName.ToString());

  //这里返回的是空的

  Console.WriteLine(ServerConnection.ConnectAsUserPassword.ToString());

  //返回的是空

  Console.ReadLine();

  //下面的形式比较灵活,使用SQL Server登录模式

  //也使用了WIndows的认证模式,这里我们使用的登录用户是通过模拟实现的,

  也就是登录的用户不是当前在Windows中运行的用户

  ServerConnection ServerConnection = new ServerConnection();

  SQLCommand cmd =

  new SQLCommand(”SELECT SUSER_NAME()”,

  ServerConnection.SQLConnectionObject);

  ServerConnection.ServerInstance = “7D87EB54AFCA4D2″;

  //根据LoginSecure属性来决定是什么模式登录数据库

  //LoginSecure=false,表示使用SQL Server登录方式,需要提供sa和对应的密码,

  或者其他的用户名和密码

  /*

  ServerConnection.LoginSecure = false;

  ServerConnection.Login = “sa”;

  ServerConnection.Password = “qeilf0327″;

  //这里提供一种加密的方式

  SecureString spwd = new SecureString();

  spwd.AppendChar(’q');

  spwd.AppendChar(’e');

  spwd.AppendChar(’i');

  spwd.AppendChar(’l');

  spwd.AppendChar(’f');

  spwd.AppendChar(’0′);

  spwd.AppendChar(’3′);

  spwd.AppendChar(’2′);

  spwd.AppendChar(’7′);

  spwd.MakeReadOnly();

  Console.WriteLine(spwd.ToString());

  //返回的字符串System.Security.SecureString

  localhost =

  new ServerConnection(

  “localhost”, name, spwd);

  Console.WriteLine(localhost.Password);

  Console.ReadLine();

  */

  //根据LoginSecure属性来决定是什么模式登录数据库

  //LoginSecure=true,表示使用Windows认证的方式,需要提供系统的用户的

  ServerConnection.LoginSecure = true;//这种方式为Windows认证的方式,

  //如果至此我们什么都不设置的话,就是当前登录的用户

  ServerConnection.ConnectAsUser = true;//如果将这个属性设置为true,

  必须要相应设置下面的两个属性

  ServerConnection.ConnectAsUserName = @”SQLUser”;

  //SQLUser,是我在系统中建立的一个管理员用户

  ServerConnection.ConnectAsUserPassword = @”chenleiilf)#27″;

  /*下面的是我们的输出

  LogonUser succedded

  7D87EB54AFCA4D2SQLUser

  */

  ServerConnection.Connect();

  //连接建立起来的时候,我们可以看看当前的状态,并输出当前登录的用户

  if (ServerConnection.IsOpen)

  {

  Console.WriteLine(ServerConnection.TrueLogin);

  }

  Console.WriteLine(cmd.ExecuteScalar());//返回的结果是7D87EB54AFCA4D2

  Administrator

  Console.ReadLine();

  2、连接数据库,获取数据库的列表

  using microsoft.SQLServer.Management.Smo;

  //Server Server = new Server(args[0]);

  //Server Server = new Server(”localhost”);//本地的

  //Server Server = new Server();//默认的,只有一个实例的时候

  Server Server = new Server(”7D87EB54AFCA4D2″);//计算机的名字

  foreach (Database database in Server.Databases)

  

  Console.ReadLine();

  //补充另外一种方法,来获取服务器中的所有数据库

  SQLConnectionStringBuilder sb =

  new SQLConnectionStringBuilder();

  sb.DataSource = “localhost”;

  sb.IntegratedSecurity = true;

  SQLConnection conn =

  new SQLConnection(sb.ConnectionString);

  conn.Open();

  SQLCommand cmd = new SQLCommand(

  @”SELECT dtb.name AS [Name] FROM

  master.sys.databases AS dtb

  ORDER BY [Name] ASC”,

  conn);

  SQLDataReader rdr = cmd.ExecuteReader();

  while(rdr.Read())

  

  //获取数据下面的表

  Server Server = new Server();

  Console.WriteLine(Server.Information.Product

  + ” ” + Server.Information.ProductLevel

  + ” ” + Server.Information.VersionString);

  foreach (Database db in Server.Databases)

  {

  Console.WriteLine(”Database: ” + db.Name);

  foreach (Table tb in db.Tables)

  {

  Console.WriteLine(” table: ” + tb.Name);

  }

  }

  3、连接数据库,获取数据库对象的URN,如,表,数据库,存储过程,程序集等

  using microsoft.SQLServer.Management.Common;

  using microsoft.SQLServer.Management.Smo;

  static void Main(string[] args)

  {

  Server localhost = new Server(”localhost”);

  Database firstDatabase = localhost.Databases[0];

  table table = firstDatabase.Tables[0];

  Console.WriteLine(firstDatabase.Name.ToString());

  Console.WriteLine(table.Name.ToString());

  Urn firstUrn = firstDatabase.Urn;

  //Server[@Name=’7D87EB54AFCA4D2′]/Database[@Name=’AdventureWorks’]

  Console.WriteLine(firstUrn.ToString());

  Urn firstTable = table.Urn;

  /*Server[@Name=’7D87EB54AFCA4D2′]

  /Database[@Name=’AdventureWorks’]/Table

  [@Name=’AWBuildVersion’ and @Schema=’dbo’]

  */

  Console.WriteLine(firstTable.ToString());

  //看看存储过程,URN,样子是怎样的

  if (firstDatabase.StoredProcedures.Count != 0)

  {

  StoredProcedure sp = firstDatabase.StoredProcedures[0];

  Console.WriteLine(sp.Urn.ToString());

  }

  //触发器

  if (firstDatabase.Triggers.Count != 0)

  {

  DatabaseDdlTrigger tigger = firstDatabase.Triggers[0];

  Console.WriteLine(tigger.Urn.ToString());

  }

  //视图

  if (firstDatabase.Views.Count != 0)

  {

  View view = firstDatabase.Views[0];

  Console.WriteLine(view.Urn.ToString());

  }

  //用户

  if(firstDatabase.Users.Count!=0)

  {

  foreach (User user in firstDatabase.Users)

  

  }

  Console.WriteLine(firstDatabase.UserName.ToString());//dbo

  Console.WriteLine(firstDatabase.ActiveConnections.ToString());//0

  Console.WriteLine(firstDatabase.ActiveDirectory.Urn.ToString());

  if(firstDatabase.Assemblies.Count!=0)

  {

  foreach(SQLAssembly assembly in firstDatabase.Assemblies)

  

  }

  localhost.ConnectionContext.Disconnect();

  //

  Server localhost1 = new Server(”localhost”);

  Database tryAgain = localhost1.GetSmoObject(firstUrn) as Database;

  Console.WriteLine(firstDatabase.Name.ToString());

  Console.ReadLine();

  }

  4、创建和删除表,数据库

  Server localhost = new Server();

  //必须输入本机的名字,7D87EB54AFCA4D2,localhost似乎不行

  Database NorthWind = localhost.GetSmoObject(

  “Server[@Name=’7D87EB54AFCA4D2′]/Database[@Name=’NorthWind’]”) as

  Database;

  table t = new table(NorthWind, “MyTable”);

  t.Columns.Add(new Column(t, “ID”, DataType.Int));

  t.Columns.Add(new Column(t, “Description”, DataType.NVarChar(200)));

  t.Create();

  Console.WriteLine(”Successfully!!”);

  //一种比较容易理解的方法

  static void AddTable(string ServerName, string databaseName, string tableName,

  string columnName)

  {

  Server Server = new Server(ServerName);

  Database database = Server.Databases[databaseName];

  table table = new table(database, tableName);

  Column column = new Column(table, “ID”, DataType.Int);

  column.Identity = true;

  table.Columns.Add(column);

  Index primary = new Index(table, “PK_” + tableName);

  primary.IndexKeyType = IndexKeyType.DriPrimaryKey;

  primary.IndexedColumns.Add(new IndexedColumn(primary, “ID”));

  table.Indexes.Add(primary);

  column = new Column(table, columnName, DataType.VarChar(256));

  table.Columns.Add(column);

  table.Create();

  }

  //删除数据库中的表

  table Test456 = canopus5.GetSmoObject(

  @”Server[@Name=’7D87EB54AFCA4D2′]

  /Database[@Name=’NorthWind’]

  /Table[@Name=’MyTable’ and @Schema=’dbo’]”)

  as table;

  Test456.Drop();

  5、查询等操作

  //学习会使用SMO的连接对象,与SQLCommand结合进行查询,执行SQL语句

  ServerConnection ServerConnection = new ServerConnection();

  ServerConnection.Connect();

  SQLCommand cmd = new SQLCommand(

  “Select * from pubs..authors”, ServerConnection.SQLConnectionObject);

  6、脚本的操作

  using microsoft.SQLServer.Management.Smo;

  using system.Collections.Specialized;//StringCollection

  Server Server = new Server();

  Database database = Server.Databases[”northwind”];

  string tableName = “mytest”;

  string columnName = “name”;

  table table = new table(database, tableName);

  Column column = new Column(table, “ID”, DataType.Int);

  column.Identity = true;

  table.Columns.Add(column);

  Index primary = new Index(table, “PK_” + tableName);

  primary.IndexKeyType = IndexKeyType.DriPrimaryKey;//需要添加引用

  microsoft.SQLServer.SQLEnum文件

  primary.IndexedColumns.Add(new IndexedColumn(primary, “ID”));

  table.Indexes.Add(primary);

  column = new Column(table, columnName, DataType.VarChar(256));

  table.Columns.Add(column);

  table.Create();

  ScriptingOptions so = new ScriptingOptions();

  //so.ScriptDrops = true;

  StringCollection sc = new StringCollection();

  //customer.Script(

  sc = table.Script(so);

  foreach (String s in sc)

  

  Console.ReadLine();

  }

  /*

  * 下面是输出的内容,就是创建的脚本

  SET ANSI_NULLS ON

  SET QUOTED_IDENTIFIER ON

  CREATE table [dbo].[mytest](

  [ID] [int] IDENTITY(1,1) NOT NULL,

  [name] [varchar](256) COLLATE SQL_Latin1_General_CP1_CI_AS NULL

  ) ON [PRIMARY]

  */

  }

  }

  7、配置管理

  using microsoft.SQLServer.Management.Smo;

  using microsoft.SQLServer.Management.Smo.Wmi;

  //可以获取,本地计算机的信息,下面演示的服务的列表

  ManagedComputer mc = new ManagedComputer();

  Console.WriteLine(mc.Name);

  foreach (Service s in mc.Services)

原创粉丝点击