Question

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;
Was it helpful?

Solution 3

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

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

OTHER TIPS

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top