2013-02-01 31 views
-2

我需要對sql-server 2008 R2做一些sql查詢。命令是:在c中執行sql命令的最佳方法#

C:> sqlcmd –S 
.\APPSDB 
1> use 
Example_database 
2> go 
1> Select SiteName, SiteID, Platform, Description, AdminUser from dbo.ExampleInfo 
2> go 

我想在C#中開發一個控制檯應用程序來運行此查詢。我的問題是:什麼是適當的方式來做到這一點?我應該把上面的命令放到一個SQL腳本中,並使用一個進程來執行這個腳本,或者我應該使用C#的SQL API如SqlConnection這樣做嗎?例如:

string cmdStr = @"....." //the above command 
using (var connection = new SqlConnection(ConnectionString)) 
{ 
    using (var command = connection.CreateCommand()) 
    { 
     connection.Open(); 
     command.CommandText = cmdStr; 
     using (var reader = command.ExecuteReader()) 
     { 
      do 
      { 
       while (reader.Read()) 
       {    
        Console.WriteLine(reader["SiteName"].ToString()); 
        Console.WriteLine(reader["SiteName"].ToString()); 
        // the rest 
       } 
      Console.WriteLine("--next command--"); 
     } while (reader.NextResult()); 
    } 
} 
+0

這是你需要做出選擇。如果此應用程序開始增長(因爲我們都知道大多數應用程序都這樣做),您應該使用sql連接對象並調用一個存儲過程。否則,腳本是好的。 – JonH

+0

爲什麼downvote我qustion?我有一個SQL Server實例APPSDB下的幾個數據庫。 – ericyoung

+1

@JonH meh; sprocs可能被高估;在大多數情況下,參數化SQL非常合適 –

回答

1

對此,無需sqlcmd

CommandText屬性應包含查詢僅是這樣的:

string cmdStr = @"Select SiteName, SiteID, Platform, Description, AdminUser 
        from dbo.ExampleInfo"; 
+0

我在一個sql server實例下有幾個數據庫。我想我需要使用「使用Example_Database」或「Use_Example_Database1」等單個cmdStr可能無法正常工作。 – ericyoung

+0

@ericyoung這應該在連接字符串中,在連接字符串屬性中提供。 –

+0

@eric你根本不需要那個:連接字符串belogs –