I have a table which contains null values and I need to get data from the table using SqlDataReader. I can't figure out how I can safely cast DBNull to int.
I'm doing it in this way at the moment:
...
reader = command.ExecuteReader();
while (reader.Read()) {
int y = (reader["PublicationYear"] != null) ? Convert.ToInt32(reader["PublicationYear"]) : 0;
...
}
...
but getting a Object cannot be cast from DBNull to other types. when PublicationYear is null.
How can I get the value safely?
Thanks.
You should compare reader["PublicationYear"] to DBNull.Value, not null.
DBNull is not the same as null. You should try something like this instead:
int y = (reader["PublicationYear"] != DBNull.Value) ? ...
int ord = reader.GetOrdinal("PublicationYear");
int y = reader.IsDBNull(ord) ? 0 : reader.GetInt32(ord);
Or, alternatively:
object obj = reader["PublicationYear"];
int y = Convert.IsDBNull(obj) ? 0 : (int)obj;
You should explicitly check if the value returned is of type DBNull
while (reader.Read()) {
int y = (!reader["PublicationYear"] is DBNull) ? Convert.ToInt32(reader["PublicationYear"]) : 0;
...
}
In fact, you can do this comparison by value as well as type:
reader["PublicationYear"] != DBNull.Value
In short - you can expect DBNull to be returned for nulls from the database, rather than null itself.
as an alternative you can do the following.
as you are converting DBNull to 0, alter the procedure that does the select. so that the select itself returns zero for a null value.
snippet to demonstrate the idea
SELECT ...
,ISNULL (PublicationYear, 0) as PublicationYear
...
FROM sometable
advantage of this is that, no additional checking is needed in your code.
Change
reader["PublicationYear"] != null
to
reader["PublicationYear"] != DBNull.Value
That's the error: (reader["PublicationYear"] != null)
You should test for DBNull.Value....
Change your test from (reader["PublicationYear"] != null) to (reader["PublicationYear"] != DBNull.Value).
Database null values should be compared with DBNull.Value:
reader = command.ExecuteReader();
while (reader.Read())
{
int y = (reader["PublicationYear"] != DBNull.Value) ? Convert.ToInt32(reader["PublicationYear"]) : 0;
...
}
Related
I´m developing an aspect using spring aop.
We usually use JoinPoint as object to retrieve class name, method name, ...
I´m doing this:
String className = joinPoint.getTarget() != null && joinPoint.getTarget().getClass() != null && joinPoint.getTarget().getClass().getName() != null ? joinPoint.getTarget().getClass().getName() : "";
String methodName = joinPoint.getSignature() != null && joinPoint.getSignature().getName() != null ? joinPoint.getSignature().getName() : "";
I have to do this? I never on tutorials or projects do this. Why not?
How can a joinPoint be null.
The reason an advice gets called is because its pointcut has matched with a method and the advice gets executed. So, There's no point in checking if its null.
It's like this.
boolean isInteger(int a) {
if(a is an Integer) {
return true;
}
return false;
}
see there's no point of this function. Checking if joinpoint is null falls under the same style.
I want to insert the below default values when i am running the service i got this below error any one please tell me how to resolve.
Runtime error in script ("Process: 'CustomPersonalGS Practice' ProcessItem: 'Initialize' Type: 'ITEM'" -1:-1).TypeError: Cannot read property "parameters" from null
//Initialise SQL Query List
tw.local.sqlQueries = new tw.object.listOf.SQLStatement();
tw.local.sql = "";
tw.local.customerPD = new tw.object.customerPD1BO();
tw.local.customerPD.customerPersonalDetailsList = new tw.object.listOf.customerSpecificPersonalDetailsListBO();
var custPersonalDetails = new tw.object.customerSpecificPersonalDetailsListBO();
custPersonalDetails.customerId = "8467";
custPersonalDetails.custPersonalDetailsId = "8";
custPersonalDetails.isBPMEnabled = true;
custPersonalDetails.isCCPEnabled = true;
custPersonalDetails.isCCPMandatory = true;
custPersonalDetails.isLatestVersion = true
tw.local.customerPD.customerPersonalDetailsList.insertIntoList(tw.local.customerPD.customerPersonalDetailsList.listLength, custPersonalDetails);
tw.local.sql = "INSERT INTO CUSTOMPERSONALDETAILSQUESTION(CUSTOMERID,CUSTPERSONLADETAILSID,ISBPMENABLED,ISCCPENABLED,ISCCPMANDATORY,ISLATESTVERSION) VALUES (?,?,?,?,?,?) ";
function addSQLStatement() {
tw.local.sqlQueries[tw.local.sqlQueries.listLength] = new tw.object.SQLStatement();
}
function addParam(value,type,mode) {
log.info("VALUE :" + value);
var newParam = new tw.object.SQLParameter();
newParam.value = value;
newParam.type = type;
newParam.mode = mode;
if( tw.local.sqlQueries == null){
tw.local.sqlQueries = new tw.object.listOf.SQLStatement();
}
if( tw.local.sqlQueries[tw.local.sqlQueries.listLength] == null ){
tw.local.sqlQueries.insertIntoList(tw.local.sqlQueries.listLength, new tw.object.SQLStatement());
}
if(tw.local.sqlQueries[tw.local.sqlQueries.listLength].parameters == null ){
tw.local.sqlQueries[tw.local.sqlQueries.listLength].parameters = new tw.object.listOf.SQLParameter();
}
var paramsLength = tw.local.sqlQueries[tw.local.sqlQueries.listLength].parameters.listLength;
tw.local.sqlQueries[tw.local.sqlQueries.listLength].parameters[paramsLength] = newParam;
}
for(var i=0;i<tw.local.customerPD.customerPersonalDetailsList.listLength;i++){
addSQLStatement(tw.local.sql);
addParam(tw.local.customerPD.customerPersonalDetailsList[i].customerId,"VARCHAR","IN");
addParam(tw.local.customerPD.customerPersonalDetailsList[i].custPersonalDetailsId,"VARCHAR","IN");
var yesNoFlag = "N";
if(tw.local.customerPD.customerPersonalDetailsList[i].isBPMEnabled){
yesNoFlag="Y";
addParam(yesNoFlag,"CHAR","IN");
}
yesNoFlag = "N";
if(tw.local.customerPD.customerPersonalDetailsList[i].isCCPEnabled){
yesNoFlag="Y";
addParam(yesNoFlag,"CHAR","IN");
}
yesNoFlag = "N";
if(tw.local.customerPD.customerPersonalDetailsList[i].isCCPMandatory){
yesNoFlag="Y";
addParam(yesNoFlag,"CHAR","IN");
}
yesNoFlag = "N";
if(tw.local.customerPD.customerPersonalDetailsList[i].isLatestVersion){
yesNoFlag="Y";
addParam(yesNoFlag,"CHAR","IN");
}
}
You didn't initialize the parameter list in your SQL as far as I can tell. That is on line 38 you call -
var paramsLength = tw.local.sqlQueries[tw.local.sqlQueries.listLength].parameters.listLength;
However when you create the entry in the tw.local.sqlQueries, you didn't initialize the parameter array. I'll also note that your addSQLStatement() function ignore the sql input (and that value is hard coded, so really you don't need to pass it in). I think if you change addSQLStatement to be something like -
function addSQLStatement(query) {
var targetQuery = new tw.object.SQLStatement();
targetQuery.sql = query;
tagetQuery.params = new tw.object.listOf.SQLParameter();
tw.local.sqlQueries[tw.local.sqlQueries.listLength] = targetQuery;
}
then your code will work. Additionally you could actually return targetQuery from this function and then pass it to the "addParams" method eliminating the need to find the last one in the array. Alternatively insert it in the beginning of the array instead and just update the 0th item instead of the last.
-AP
This comparison will never work properly. array[array.length] will always be null (line 35).
if (tw.local.sqlQueries[tw.local.sqlQueries.listLength].parameters == null ){
In addition, in the next lines, if you want to work with the last element of the list, you might want to use something like array[array.length - 1]. Personally, I'd use some temporary variable, do some stuff with it and insert it into the list at the end (similar to #Drux's answer).
When I try to evaluate a boolean expression that contain a variable with null value or evaluate a undefined variable, the parser not work as I expected, it does not fail, rather than, it assume the null variable (or the undefined variable) as big negative number (I guess...).
Here the Test class I wrote to show this:
public class SpELTest {
#Test(expected = Exception.class)
public void evaluateNullVariable() {
ExpressionParser parser = new SpelExpressionParser();
StandardEvaluationContext context = new StandardEvaluationContext();
context.setVariable("PERFORMANCE", null);
Boolean result = (Boolean)parser.parseExpression("#PERFORMANCE < 100").getValue(context);
assertTrue(result); // no expected result
}
#Test(expected = Exception.class)
public void evaluateUndefinedVariable() {
ExpressionParser parser = new SpelExpressionParser();
Boolean result = (Boolean)parser.parseExpression("#UNDEFINED < 100").getValue();
assertTrue(result); // no expected result
}
}
any idea of this behavior or how to avoid it?
"#PERFORMANCE == null ? false : #PERFORMANCE < 100"
I have the following code:
public fun findSomeLikeThis(): ArrayList<T>? {
val result = Db4o.objectContainer()!!.queryByExample<T>(this as T) as Collection<T>
if (result == null) return null
return ArrayList(result)
}
If I call this like:
var list : ArrayList<Person>? = p1.findSomeLikeThis()
for (p2 in list) {
p2.delete()
p2.commit()
}
It would give me the error:
For-loop range must have an 'iterator()' method
Am I missing something here?
Your ArrayList is of nullable type. So, you have to resolve this. There are several options:
for (p2 in list.orEmpty()) { ... }
or
list?.let {
for (p2 in it) {
}
}
or you can just return an empty list
public fun findSomeLikeThis(): List<T> //Do you need mutable ArrayList here?
= (Db4o.objectContainer()!!.queryByExample<T>(this as T) as Collection<T>)?.toList().orEmpty()
try
for(p2 in 0 until list.count()) {
...
...
}
I also face this problem when I loop on some thing it is not an array.
Example
fun maximum(prices: Array<Int>){
val sortedPrices = prices.sort()
for(price in sortedPrices){ // it will display for-loop range must have iterator here (because `prices.sort` don't return Unit not Array)
}
}
This is different case to this question but hope it help
This can also happen in Android when you read from shared preferences and are getting a (potentially) nullable iterable object back like StringSet. Even when you provide a default, the compiler is not able to determine that the returned value will never actually be null. The only way I've found around this is by asserting that the returned expression is not null using !! operator, like this:
val prefs = PreferenceManager.getDefaultSharedPreferences(appContext)
val searches = prefs.getStringSet("saved_searches", setOf())!!
for (search in searches){
...
}
I am using the following code to check for values of 1 or 0 stored in a dictionary file called 'myDict'. At position 'block003stored' is the value 1 and at all the other positions it's 0. If I use the following code I always get 0 returned for all positions:
for (int i = 1 ; i < 100 ; i++) {
if(myDict)
{
UIImageView *imageV = (UIImageView *)[self.view viewWithTag:i];
int myInt = [[myDict objectForKey:#"block%.3istored"] intValue];
NSLog (#"value of i %d", i);
NSLog (#"myInt %d", myInt);
if (myInt == 1) imageV.hidden = FALSE;
}
}
}
However if I change the objectForKey to specifically #"block003stored":
int myInt = [[myDict objectForKey:#"block003stored"] intValue];
I get the correct value of 1 returned. I can't see why the code isn't working when I use the %.3i instead of 001, 002, 003 etc?
Try in a separate line:
NSString *indexStr = [NSString stringWithFormat:#"block%.3dstored", i]; Then use the objectForKey:indexStr];
You were asking the dictionary to get the object with the key of "block%.3istored", which didn't exist. You need to apply formatting to get i in there.
The code in the loop is using #"block%.3istored" as a literal string. There's nothing in what you've written to format the string with the i variable. Look at NSString's stringWithFormat: as a way of dynamically building the key.