使用表名列表删除SQLite表

时间:2014-12-31 12:29:39

标签: c# sqlite windows-8.1

我试图通过使用列表中的表名来drop a collection of tables,然后获取每个字符串的类型并删除它:

List<string> models = new List<string> { "WebBrowser", "Notebook", "Members"};

foreach (string mod in models)
{

    Type type = Type.GetType(mod));
    using (var dbConn = new SQLiteConnection(app.DBPath))
    {
        dbConn.RunInTransaction(() =>
        {
            dbConn.DropTable<type>();
            //dbConn.DropTable<WebBrowser>();
            dbConn.Dispose();
            dbConn.Close();
        });
    }
}

问题:我不能用这种方式删除表, DropTable 需要类的名称(例如 WebBrowser )而且我不喜欢我想单独删除每个表(即dbConn.DropTable&lt; WebBrowser&gt;();),因为我有超过50个表要删除。

错误:“无法找到类型或命名空间名称'类型'”。 (由于我的命名空间中没有类'type',因此预计会出现此错误。

2 个答案:

答案 0 :(得分:2)

您可以在SQLite中使用SQL命令删除表。您需要做的就是迭代您的集合并每次构建一个SQL字符串,并执行它

List<string> models = new List<string> { "WebBrowser", "Notebook", "Members"};

foreach (string mod in models)
{
    using (var dbConn = new SQLiteConnection(app.DBPath))
    {
        SQLiteCommand command = new SQLiteCommand(dbConn);
        command.CommandText = string.Format("DROP TABLE {0};", mod);
        command.ExecuteNonQuery();
    }
}

我不确定这种语法对你的情况是否完全正确(我在Windows 8.1中只使用sqlite-net),但一般方法是合理的

答案 1 :(得分:1)

您可以像这样创建自己的Extensionmethod:

public static class SQLiteConnectionExtensions
{
    public static int DropTable(this SQLiteConnection conn, string tableName)
    {
        var query = string.Format("drop table if exists \"{0}\"", tableName);
        return conn.Execute(query);
    }
}

然后像这样使用它:

var tables = new List<string> { "WebBrowser", "Notebook", "Members" };

using (var dbConn = new SQLiteConnection(app.DBPath))
{
    dbConn.RunInTransaction(() =>
    {
        foreach (string table in tables)
        {
            dbConn.DropTable(table);
        }
    });
}
相关问题