【问题标题】:How to drop table in Access if exists如果存在,如何在 Access 中删除表
【发布时间】:2011-05-01 10:09:06
【问题描述】:

我使用 C# 并访问数据库。
mysql中有一条删除表的语句,如下所示:

drop table if exists t_table

那么您知道 Access 的类似声明吗?

【问题讨论】:

  • 作为this question 的答案发布的 SQL 应该可以满足您的需求

标签: c# ms-access


【解决方案1】:


我不知道 Access 中有这样的 SQL 语句。
但是,您可以执行以下操作之一:

  • 尝试删除表而不检查是否存在,捕获异常(如果没有找到表,它应该有特定的代码)并忽略它。

  • 如果表存在,请尝试检查Access隐藏表MSysObjects(但是使用ADO,它默认没有权限)

  • 使用如下代码(坏处:删除表不返回受影响的记录):

    using (OleDbConnection conn = new OleDbConnection(@"Provider=Microsoft.JET.OLEDB.4.0;data source=c:\myDatabase.mdb"))
    {
        conn.Open();
    
        string tableToDelete = "myTable";   //table name
        bool tableExists = false;
    
        DataTable dt = conn.GetSchema("tables");
    
        foreach (DataRow row in dt.Rows)
        {
            if (row["TABLE_NAME"].ToString() == tableToDelete)
            {
                tableExists = true;
                break;
            }
        }
    
        if (tableExists)
        {
            using (OleDbCommand cmd = new OleDbCommand(string.Format("DROP TABLE {0}", tableToDelete), conn))
            {
                cmd.ExecuteNonQuery();
                MessageBox.Show("Table deleted");
            }
        }
        else
            MessageBox.Show(string.Format("Table {0} not exists", tableToDelete));
    }
    

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-06-06
    • 2011-12-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-06-07
    • 1970-01-01
    相关资源
    最近更新 更多