• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 1169
  • Last Modified:

DBNull.Value.ToString why it does not work?

Hi, I'm trying to use DBNull.Value.ToString in sql statement to insert nul value but it does not work, any suggestion?
0
Abdu_Allah
Asked:
Abdu_Allah
3 Solutions
 
Guy Hengel [angelIII / a3]Billing EngineerCommented:
that won't work indeed...

if you used a Command object with Parameters, then you can assign the DBNull.Value as such to the parameter, then it will work.

please show your code.
0
 
Abdu_AllahAuthor Commented:

Dim fx as string
If x= 1 then
 fk = DBNull.Value.ToString
else
 fk = 5
end if
 
strSQL = "Insert into mytable(...,fk,...) values("... + fk + ")"

Open in new window

0
 
Guy Hengel [angelIII / a3]Billing EngineerCommented:
you "could" make your code like this:
Dim fx as string
If x= 1 then
 fk = "NULL"
else
 fk = 5
end if
 
strSQL = "Insert into mytable(...,fk,...) values("... + fk + ")"

Open in new window

0
Concerto's Cloud Advisory Services

Want to avoid the missteps to gaining all the benefits of the cloud? Learn more about the different assessment options from our Cloud Advisory team.

 
Guy Hengel [angelIII / a3]Billing EngineerCommented:
however, I repeat, using the db Command + Parameter objects would be better...
0
 
Abdu_AllahAuthor Commented:
Isn't it possible to do that in the way I put?
0
 
Guy Hengel [angelIII / a3]Billing EngineerCommented:
actually, I never tried the ToString of the dbnull.value, so it might work.... for numerical data types columns.
creating the sql ad-hoc like that is subject to be sql-injected. so I don't really like giving advice on using it.

take this less for using SqlCommand and SqlParameter objects, with the DBNull.Value being assigned for the parameter object will work just fine.
http://www.csharp-station.com/Tutorials/AdoDotNet/Lesson06.aspx
0
 
Éric MoreauSenior .Net ConsultantCommented:
1. You declare "fx" and use "fk".

2. Even if you were using the correct variable name, DBNull.Value.Tostring returns an empty string so it wouldn't work.
0
 
tiagosalgadoCommented:
You can ignore the field that you're trying to set a null value in your IF statement.


Dim fk as string
If x= 1 then
 strSQL = "Insert into mytable(...) values(...)"
else
 fk = 5
 strSQL = "Insert into mytable(...,fk,...) values("... + fk + ")"
 
end if
 

Open in new window

0

Featured Post

What does it mean to be "Always On"?

Is your cloud always on? With an Always On cloud you won't have to worry about downtime for maintenance or software application code updates, ensuring that your bottom line isn't affected.

Tackle projects and never again get stuck behind a technical roadblock.
Join Now