• 如何通过代码远程控制Microsoft Sql Server


    微软的Microsoft Sql Server有个SDK库,里面有相当于Manager功能各种命令,只要引用相应的Dll,就可以执行相应的命令,现在就以远程执行文件(.sql)为例。

    一、引用相应的DLL (version: sql 2008)

    引用以下DLL,文件所在位置是安装Mssql目录+Microsoft SQL Server\100\SDK\Assemblies

    Microsoft.SqlServer.ConnectionInfo.dll
    Microsoft.SqlServer.Dmf.dll
    Microsoft.SqlServer.Management.Sdk.Sfc.dll
    Microsoft.SqlServer.ServiceBrokerEnum.dll
    Microsoft.SqlServer.Smo.dll
    Microsoft.SqlServer.SqlClrProvider.dll
    Microsoft.SqlServer.SqlEnum.dll

    二、方法

    #region Execute file of sql
            public bool ExecuteSqlFile(string userId, string password, string server, string file)
            {
                bool result = true;
                try
                {
                    string sqlConnectionString = string.Format("server={2};database=master;uid={0};pwd={1}", userId, password, server);

                    FileInfo fileInfo = new FileInfo(file);

                    StringBuilder script = new StringBuilder(fileInfo.OpenText().ReadToEnd());
                    SqlConnection conn = new SqlConnection(sqlConnectionString);

                    Microsoft.SqlServer.Management.Smo.Server sqlServer = new Microsoft.SqlServer.Management.Smo.Server(new Microsoft.SqlServer.Management.Common.ServerConnection(conn));

                    sqlServer.ConnectionContext.ExecuteNonQuery(script.ToString());
                }
                catch
                {
                    result = false;
                }
                return result;
            }
            #endregion

    可要引用此方法就可以执行向远程数据库执行文件了,引用的方法如下:

    result = ExecuteSqlFile(dbUsername, dbPassword, dbServer, fileName);

  • 相关阅读:
    Python GUI编程实例
    Python MySQL事务、引擎、索引及第三方库sqlalchemy
    Python 魔法方法简介
    Python sax模块(SAX解析XML)
    Python minidom模块(DOM写入和解析XML)
    【LOJ】#2432. 「POI2014」代理商 Couriers
    【51nod】1559 车和矩形
    【LOJ】#2430. 「POI2014」沙拉餐厅 Salad Bar
    【LOJ】#2105. 「TJOI2015」概率论
    【BZOJ】1336: [Balkan2002]Alien最小圆覆盖
  • 原文地址:https://www.cnblogs.com/lovewife/p/1430196.html
Copyright © 2020-2023  润新知