如何通過代碼遠端控制Microsoft Sql Server)

來源:互聯網
上載者:User

微軟的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);

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.