我需要對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());
}
}
這是你需要做出選擇。如果此應用程序開始增長(因爲我們都知道大多數應用程序都這樣做),您應該使用sql連接對象並調用一個存儲過程。否則,腳本是好的。 – JonH
爲什麼downvote我qustion?我有一個SQL Server實例APPSDB下的幾個數據庫。 – ericyoung
@JonH meh; sprocs可能被高估;在大多數情況下,參數化SQL非常合適 –