具有 NULL 值的 Npgsql 参数,vb.net

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/16348500/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-17 13:28:27  来源:igfitidea点击:

Npgsql parameters with NULL value, vb.net

vb.netpostgresqlparametersnpgsql

提问by user2344922

I'm running through a loop adding parameters, when I get to a NULL, the program punts. My statement looks like this:

我正在运行添加参数的循环,当我达到 NULL 时,程序就会停止运行。我的声明是这样的:

mysql = "Insert into TABLE (field1) VALUES (:Col1)"

mycomm = New NpgsqlCommand (mySQL, conn)

myComm.Parameters.Add("Col" & cCnt, NpgsqlTypes.NpgsqlDbType.Double).Value = Obj.value

myComm.ExecuteNonQuery()

This works fine if Obj.value is not empty, but if Obj.value is nothing, my Execute statement fails. I'd like to just insert a NULL value into the DB. Any ideas? Thanks for any help!

如果 Obj.value 不为空,这可以正常工作,但如果 Obj.value 什么都没有,我的 Execute 语句就会失败。我只想在数据库中插入一个 NULL 值。有任何想法吗?谢谢你的帮助!

回答by Steve

To insert a NULL value in the database field, you need to pass the DBNull.Valueto your parameter

要在数据库字段中插入 NULL 值,您需要将DBNull.Value传递给您的参数

You could use the VB.NET ternary operatorto check if Obj itself is Nothing or if Obj.Value is nothing and in that case (true) pass the DBNull.Valueinstead of the Obj.Value

您可以使用VB.NET 三元运算符来检查 Obj 本身是否为 Nothing 或 Obj.Value 是否为空,在这种情况下(真)传递DBNull.Value而不是 Obj.Value

myComm.Parameters.Add("Col" & cCnt, NpgsqlTypes.NpgsqlDbType.Double).Value = 
                      If(Obj Is Nothing OrElse Obj.Value Is Nothing, DBNull.Value, Obj.value))