在 vb.net 中为字符串变量插入 NULL 值
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/40310610/
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
Inserting NULL value for a string variable in vb.net
提问by Kals
I'm trying to insert a NULL value to a variable of type string. Please let me know the possible ways to do it. I googled about this problem and found that DBNul.value can be assigned to the particular variable that has to be inserted as NULL. When i tried it errored out saying DB.Null cannot be converted to type system.string.
我正在尝试将 NULL 值插入到字符串类型的变量中。请让我知道可能的方法。我用谷歌搜索了这个问题,发现可以将 DBNul.value 分配给必须作为 NULL 插入的特定变量。当我尝试它时出错说 DB.Null 无法转换为 type system.string。
回答by Quima
You can assign a NULL value to a string in by setting it to nothing
您可以通过将字符串设置为空来为字符串分配 NULL 值
dim MyString as string
MyString = nothing
A VBNull.Value is generally used to apply a null value when using a database insertion, or to verify if the recieved value is null.
VBNull.Value 通常用于在使用数据库插入时应用空值,或验证接收到的值是否为空。
EDIT:As you made clear you want to add a null value to a database, this can be achieved by setting the null value directly in the command object:
编辑:正如您明确表示要向数据库添加空值,这可以通过直接在命令对象中设置空值来实现:
Dim Command As New OleDb.OleDbCommand 'Use the proper database command
Command.CommandText = "INSERT INTO Table (Column1, Column2) Values (@Value1, @Value2)"
Command.Parameters.AddWithValue("@Value1", If(string.IsNullOrEmpty(MyString1), DBNull.Value, MyString1))
Command.Parameters.AddWithValue("@Value2", If(string.IsNullOrEmpty(MyString2), DBNull.Value, MyString2))
回答by djv
Using Linq to SQL or the similar Entity Framework, you can store DBNull using Nothing
使用 Linq to SQL 或类似的实体框架,您可以使用存储 DBNull Nothing
I have a simple table with...
我有一个简单的表...
CREATE TABLE [dbo].[Table_1](
[ID] [bigint] IDENTITY(1,1) NOT NULL,
[TestID] [bigint] NOT NULL,
[Description] [nchar](10) NULL,
and using this code...
并使用此代码...
Sub Main()
Using dc As New DataClasses1DataContext
Dim testNothing = New Table_1
testNothing.Description = Nothing
testNothing.TestID = 1
dc.Table_1s.InsertOnSubmit(testNothing)
Dim testEmpty = New Table_1
testEmpty.Description = ""
testEmpty.TestID = 2
dc.Table_1s.InsertOnSubmit(testEmpty)
dc.SubmitChanges()
End Using
End Sub
the contents of the table is...
表的内容是……
ID TestIDDescription
1 1 NULL
2 2
ID TestIDDescription
1 1 NULL
2 2
回答by WilRogJr
You want to use Nothing.
你想使用 Nothing。
myStringVar = Nothing
myStringVar = 无

