【问题标题】:How to check if Field can contain NULL (adFldIsNullable)如何检查字段是否可以包含 NULL (adFldIsNullable)
【发布时间】:2013-12-21 19:01:02
【问题描述】:

我已经尝试过这段代码(ASP CLASSIC):

Public Function IsNullable(MyField)
    Dim RS, SQL, Tmp
    SQL = "SELECT " & MyField & " FROM mytable WHERE 1;"
    Set RS = Server.CreateObject("ADODB.Recordset")
    RS.Open SQL, conn 'I have connection opened elsewhere, using Driver={MySQL ODBC 5.2w Driver}

    'Now check for Attributes
    Tmp = RS.Fields(MyField).Attributes
    IsNullable = 0 <> (Tmp And adFldIsNullable) '0x20
    RS.Close
    Set RS = Nothing
End Function

函数工作正常,但有时结果是错误的。例如,它为 ID 字段返回 True,该字段绝对不能为空,因为它是主索引自动增量。我怎样才能使它可靠?谢谢

添加:似乎当列设置为 AutoIncrement Not Null 时,函数工作错误...

【问题讨论】:

    标签: mysql vbscript asp-classic ado


    【解决方案1】:

    这是根据http://bugs.mysql.com/bug.php?id=3857设计的

    [21 Jul 2004 22:26] Timothy Smith(当时的高级支持工程师)

    这是因为 MySQL 将此类列的 DEFAULT 值报告为 NULL。这意味着,如果你
    在列中插入一个 NULL 值,您将获得表的下一个整数值
    auto_increment 计数器。

    它仍然有效,@kordirko 的解决方案是完全可以接受的。

    【讨论】:

    • 这不是我想要的。我不能投票,因为我是这里的新手。我可以不用检查 ID 列...谢谢。
    【解决方案2】:

    在MySql中可以查询information_schema.columns查看:

    SELECT is_nullable
    FROM information_schema.columns
    WHERE table_schema = 'my_schema'
      AND table_name   = 'table-name'
      AND column_name = 'column name'
    

    查看此演示:http://www.sqlfiddle.com/#!2/743d6/3

    【讨论】:

    • 我很确定这种方法会奏效,谢谢。但是如果我不能/不想使用 information_schema 怎么办?
    • Information_schema 是 ANSI 标准 --> en.wikipedia.org/wiki/Information_schema,很多数据库都实现了,所以查询数据库元数据是最简单的方法。如果你不喜欢它,好吧,我真的不知道其他方式。 Mayby 深入研究 ADO.NET 文档,我不知道 ADO.NET,我无能为力,但我很确定他们有一些查询表元数据的功能,例如我发现了这个:stackoverflow.com/questions/457485/…跨度>
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多