vb.net 使用 vbNull 将 NULL 插入到 sql server 数据库表中

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/18188778/
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 14:37:24  来源:igfitidea点击:

Using vbNull to insert NULL into a sql server database table

sql-servervb.net

提问by Random User

I need to insert text MALEor FEMALEinto a table depending upon the user's input.

我需要根据用户的输入将文本MALEFEMALE插入到表格中。

I used to following code to insert but the code inserts value 1if none (Male/Female)selected.

我曾经按照代码插入,但如果没有选择(男/女),代码会插入值1

query = "INSERT INTO student_profile_table(gender) VALUES(@gender)"
cmd = New SqlCommand(query, con)

If rbtmale.Checked = True Then
   cmd.Parameters.AddWithValue("@gender", "Male")
ElseIf rbtfemale.Checked = True Then
   cmd.Parameters.AddWithValue("@gender", "Female")
Else
   cmd.Parameters.AddWithValue("@gender", vbNull)
End If

con.Open()
cmd.ExecuteNonQuery()
con.Close()

Need some suggestions/corrections

需要一些建议/更正

回答by Brad Rem

I believe you want System.DbNull.Valueinstead of vbNull.

我相信你想要System.DbNull.Value而不是vbNull.

System.DbNull.Valueis the constant that SQL Server understands as null.

System.DbNull.Value是 SQL Server 理解为 null 的常量。

vbNullis intended to indicate if a Variant type is null.

vbNull旨在指示 Variant 类型是否为空。

回答by masteryeng

I've search in the net but I got no answer. What I did is I've used a blank image (totally white image) stored as default picture if no picture will be saved. Hoping this will help.

我在网上搜索过,但没有答案。如果没有图片将被保存,我所做的是我使用了一个空白图像(全白图像)作为默认图片存储。希望这会有所帮助。

回答by Davideveloper

I solved it this way to make set with NULL value.

我通过这种方式解决了它,以设置为 NULL 值。

 If yourVariable Is Nothing Then
    comm.Parameters.AddWithValue("@detalleDesc", DBNull.Value)
Else
    comm.Parameters.AddWithValue("@detalleDesc", yourVariable )
End If

Regards

问候