I have to build query string from string values like:

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

_cd.userName "," +

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

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

So my query would look like INSERT INTO (...) VALUES ('name', null, (...))

But when Im using that it cuts my string, so it's look like

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

Well, I know that I can use var a,b,c,d and then check if (_cd.lastLogin == "Null) a = null and put that into string, but there is many variables.

What is proper way to use it?

@EDIT: Code:

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;
有帮助吗?

解决方案 3

? operator has lower precedence then + operator. So you need to parenthesize around the usage of ? and :.

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

其他提示

you can use SqlParameter and set value with DbNull.Value

INSERT INTO (...) VALUES (@par1, @par2) command.Parameters.AddwithValue("@par1",DbNull.Value)

The proper way to make your queries is not building your queries with string, but using SqlParameters. This will give your more readable code and is better protected against sql injection.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top