C# SQLite数据库入门使用说明

2020-01-05 10:02:20王冬梅

三、基本使用

1. 判断数据文件是否存在


/// <summary>
/// 检查数据库是否存在不存在创建
/// </summary>
/// <returns></returns>
public static bool CheckDataBase()
{
 try
 {
  //判断数据文件是否存在
  bool dbExist = File.Exists("mesclient.sqlite");
  if (!dbExist)
  {
   SQLiteConnection.CreateFile("mesclient.sqlite");
  }


  return true;
 }
 catch (Exception)
 {
  return false;
 }
}

2. 判断表是否存在


/// <summary>
/// 检查数据表是否存在,不存在创建
/// </summary>
/// <returns></returns>
public static bool CheckDataTable(string connStr)
{
 try
 {
  using (SQLiteConnection conn = new SQLiteConnection(connStr))
  using (SQLiteCommand cmd = conn.CreateCommand())
  {
   conn.Open();
   cmd.CommandText = "SELECT count(*) FROM sqlite_master WHERE type = 'table' AND name = 'serverinfo'";
   object ob = cmd.ExecuteScalar();
   long tableCount = Convert.ToInt64(ob);
   if (tableCount == 0)
   {
    //创建表
    cmd.CommandText = @"
   BEGIN;
    create table serverinfo 
    (Id INTEGER PRIMARY KEY AUTOINCREMENT,Name TEXT,
    Url text,DelayTime integer,UsageCounter INTEGER,
     Status integer,CreateTime DATETIME);
    CREATE UNIQUE INDEX idx_serverInfo ON serverinfo (Name);
   COMMIT;
   ";
    //此语句返回结果为0
    int rowCount = cmd.ExecuteNonQuery();
    return true;
   }
   else if (tableCount > 1)
   {
    return false;
   }
   else
   {
    return true;
   }
  }
 }
 catch (Exception ex)
 {
  return false;
 }
}

3. 查询


string sql = "SELECT * FROM serverinfo WHERE Name =@ServerName AND Url = @Url and date(CreateTime)=date(@Date);";
Dictionary<string, object> parameters = new Dictionary<string, object>();
parameters.Add("ServerName",endpointElement.Name);
parameters.Add("Url", endpointElement.Address);
parameters.Add("Date", DateTime.Now.ToString("yyyy-MM-dd"));
DataTable dt=SqliteHelper.ExecuteQuery(connStr, sql, parameters);
if (dt.Rows.Count>0)
{
 UsageCounter = dt.Rows[0].Field<long>("UsageCounter");
 GetTime = dt.Rows[0].Field<DateTime>("CreateTime");
}

4. 新增/修改