Vb.net检查DB Mysql中是否存在没有Try Catch的表

时间:2015-10-15 21:38:01

标签: mysql vb.net

你好我想找到一个最好的方式来询问Mysql如果一个表存在,我找到很多例子,但所有等待异常的try catch这样

Try
      'do a select COUNT(*)
Catch ex as Exception
      'return True to indicate table exist
Finally 
     'clean up
End try

但我认为不是一个好方法,我想重复一遍,其他方法就是这样:

   Using cn As New MySqlConnection(cs)
            Dim restrictions(4) As String
            restrictions(2) = tblName
            Dim dbTbl As DataTable = cn.GetSchema("Tables", restrictions)
            If dbTbl.Rows.Count = 0 Then
                'Table does not exist
                Return False
            Else
                'Table exists
                Return True
            End If
            cn.Close()
            cn.Dispose()

但我有一个未设置对象的消息引用。

3 个答案:

答案 0 :(得分:0)

您可以执行此查询并查看是否有任何结果:

show tables like 'my-table-name';

答案 1 :(得分:0)

<强>更新 Mysql提供了一种方法,我认为这是执行此行的最佳方法

SELECT COUNT( * ) 
FROM information_schema.tables
WHERE table_schema =  'Database'
AND table_name =  'Table'

答案 2 :(得分:0)

您的问题是由于在发出命令之前应该打开连接这一事实引起的。如果您只是添加缺少cn.Open

的内容,那么您的第二个示例应该按原样运行
Using cn As New MySqlConnection(cs)
  Dim restrictions(4) As String
  restrictions(2) = tblName
  cn.Open()
  Dim dbTbl As DataTable = cn.GetSchema("Tables", restrictions)
  If dbTbl.Rows.Count = 0 Then
      Return False
  Else
     Return True
  End If
End Using

此外,无需关闭和处理连接,这将在End Using语句中自动完成。当然,尝试发现表是否存在捕获异常的第一种方法是完全错误的(性能,由异常驱动的代码,其他类型的异常)并且不应该被考虑。

使用GetSchema调用的代码中有一个令人困惑的地方:
该消息讨论了Null引用异常,但显然该代码中没有空对象,因为如果找不到匹配项,GetSchema应该返回初始化的DataTable
但是,如果省略cn.Open,则会获得NRE。

那么NRE来自哪里?

查看MySqlConnection的反编译代码,对GetSchema的调用是这样的

public override DataTable GetSchema(string collectionName, string[] restrictionValues)
{
    string[] strArray;
    MySqlSchemaCollection schemas;
    if (collectionName != null)
    {
        goto Label_000A;
    }
    collectionName = SchemaProvider.MetaCollection;
Label_000A:
    strArray = this.schemaProvider.CleanRestrictions(restrictionValues);
    return this.schemaProvider.GetSchema(collectionName, strArray).AsDataTable();
}

this.schemaProvider.GetSchema(....)调用的代码如下

public virtual MySqlSchemaCollection GetSchema(string collection, string[] restrictions)
{
    MySqlSchemaCollection schemas;
    if (this.connection.State == 1)
    {
        goto Label_0019;
    }
    throw new MySqlException("GetSchema can only be called on an open connection.");
Label_0019:
    collection = StringUtility.ToUpperInvariant(collection);
    schemas = this.GetSchemaInternal(collection, restrictions);
    if (schemas != null)
    {
        goto Label_0038;
    }
    throw new ArgumentException("Invalid collection name");
Label_0038:
    return schemas;
}

所以这只留下一种可能性。 schemaProvider变量未初始化。搜索Open的{​​{1}}方法我可以找到初始化schemaProvider变量的行

MySqlConnection

所以这可能是某种错误吗? 我会给那些更专家的答案。

相关问题