2010-10-01 22 views
1

假設我們想從數據庫中選擇數據,然後我們爲此寫入查詢。爲什麼我們應該在asp.net中的sql查詢之前編寫@?

例子:

SqlConnection con=new SqlConnection(Connetion name) 
string selectPkId = @"SELECT PK_ID FROM TABLE" 
SqlCommand cmd=new SqlCommand(selectPkId ,con); 

所以,我的問題是,爲什麼我們的sql前基本上都用@ query.If我不使用@在此之前,然後重新正常工作(不給任何錯誤) ,那麼需要使用「@」?請告訴我。

回答

6

這是一個逐字串。這意味着新行被保留,逃避忽略序列:

string a = "hello, world";     // hello, world 
string b = @"hello, world";    // hello, world 
string c = "hello \t world";    // hello  world 
string d = @"hello \t world";    // hello \t world 
string e = "Joe said \"Hello\" to me";  // Joe said "Hello" to me 
string f = @"Joe said ""Hello"" to me"; // Joe said "Hello" to me 
string g = "\\\\server\\share\\file.txt"; // \\server\share\file.txt 
string h = @"\\server\share\file.txt";  // \\server\share\file.txt 

MSDN參考:String Literals

這派上用場,當你想轉義序列被保留,而無需加倍逃避他們,例如:

string sql = @"UPDATE table SET comment='Hello\nWorld'" 
// equivalent to: 
string sql = "UPDATE table SET comment='Hello\\nWorld'" 

當然這是一個非常簡單的例子,但大多數時候它會給你一個更可讀的字符串。

相關問題