2013-10-01 101 views
-1

我不得不從字符串值建立查詢字符串,如:字符串和? :運營商

connString += "INSERT INTO (...) VALUES ("+ 

_cd.userName "," + 

//and there i'd like to use ?: operators: 

_cd.lastLogin == "Null" ? "null" : _cd.lastLogin "," 

所以我的查詢看起來像INSERT INTO (...) VALUES ('name', null, (...))

但是,當即時通訊使用的是它減少我的字符串,所以它看起來像

",null,1,2,'name', (...)"; 

嗯,我知道我可以使用var a,b,c,d然後檢查是否(_cd.lastLogin == "Null) a = null並將其放入字符串中,但有很多變量。

什麼是正確的使用方法?

@EDIT: 代碼:

string query = "INSERT INTO PersonLogin(...) " + Environment.NewLine + 
"VALUES (" + _cD.userID + "," 
+ "'" + _cD.number + "'," 
+ "'" + _cD.dateCreate + "','" 
+ _cD.lastLogin == "Null" ? ",null," : _cD.lastLogin + "'," 
+ _cD.taken + "," 
+ _cD.canLogin + ""+ Environment.NewLine; 
+0

對不起,我忘了 - C#。 – user13657

+15

正確的方法是使用SqlParameters。像這樣構建你的查詢是瘋狂的。 – Arran

+3

阿蘭說了些什麼。但是要回答你的問題,可能把括號用在''的所有用法上? :'。 – Jon

回答

-1

?經營者有優先級低則+運營商。所以你需要圍繞?:的使用進行加括號。

connString += ... + (_cd.lastLogin == "Null" ? "null" :"'"+ _cd.lastLogin) +"'" ...; 
+2

-1用於暗示實現的錯誤方式。看到msm2020的答案。 –

+0

@AmitRanjan我不是在暗示這一點,我試圖向OP展示他的錯誤。 –

+2

我會標記爲解決方案,因爲這是我的問題的答案,但是,正如你所說的 - 我會盡量用SqlCommand來完成。 – user13657

3

可以使用的SqlParameter和設定值與DbNull.Value

INSERT INTO(...)VALUES(@ PAR1,PAR2 @) command.Parameters.AddwithValue( 「@ PAR1」 ,DbNull.Value)

+0

我知道我可以使用SqlParameters和Command。但正如我所說,我有50 + Colums桌子,例如只有20/50是空的。所以用這個解決方案,我需要做一些類似if(value == null)然後添加nullValue else add value.value – user13657

+0

你可以在command.parameters中循環,但這是一個不好的解決方案 或 + _cD.lastLogin == null ? 「,null,」:_cD.lastLogin +「',」 – msm2020

1

正確的方法,使您的查詢的不串建立查詢,但使用SqlParameters。這將提供更多可讀代碼,並且更好地防止sql注入。