SQLite判断表格是否存在
判断表格是否存在的方法,
select count(*) from sqlite_master where type='table' and name = youTableName 这句sql语句的作用:从sqlite数据库中对类型为表格的进行计数统计 其他sqlite_master为sqllite数据库内置的名称,是固定不变的。
/// <summary>
/// 判断数据库中表格是否存在
/// </summary>
/// <param name="tableName">表名</param>
/// <param name="path">数据库路径</param>
/// <returns>是否存在</returns>
public static bool ExistTable(string tableName, string path)
{
if (System.IO.File.Exists(path) == false)
SQLiteConnection.CreateFile(path);
using (SQLiteConnection con = new SQLiteConnection(string.Format("Data Source={0};Version=3;", path)))
{
con.Open();
int result;
string count="0";
//开启事务
using (SQLiteTransaction tr = con.BeginTransaction())
{
using (SQLiteCommand cmd = con.CreateCommand())
{
string existSql = String.Format("select count(*) from sqlite_master where type='table' and name = '{0}'", tableName);
cmd.Transaction = tr;
cmd.CommandText = existSql;
//使用result = cmd.ExecuteNonQuery();这句判断返回值的方法不正确,不论是否存在返回值都为-1
SQLiteDataReader reader = cmd.ExecuteReader();
while (reader.Read())
{
count= reader[0].ToString();
}
}
//提交事务
tr.Commit();
}
con.Close();
if (count == "0")
return false;//没有该表格
else
return true;
}
}
注意:请不用使用result = cmd.ExecuteNonQuery()的返回值来判断是否存在表格。经过实践证明无论结果是否存在,返回值都为-1.
此方法经过我实践证明,请放心使用,转载请写明来源,谢谢你的阅读