C# SQLite
/// <summary> /// 创建数据库文件 /// </summary> public static void CreateDatabase() { // Data文件夹不存在时,首先创建Data文件夹 if (!Directory.Exists(AppDomain.CurrentDomain.BaseDirectory + "Data")) { Directory.CreateDirectory(AppDomain.CurrentDomain.BaseDirectory + "Data"); } // 创建数据库文件 SQLiteConnection.CreateFile(AppDomain.CurrentDomain.BaseDirectory + "Data\\Note"); // 创建并打开连接 SQLiteConnection conn = new SQLiteConnection("Data Source=" + AppDomain.CurrentDomain.BaseDirectory + "Data\\Note"); conn.Open(); // 创建Command并设置类型 SQLiteCommand cmd = conn.CreateCommand(); cmd.CommandType = CommandType.Text; // 打开自动清理数据库模式,此条命令必须放在创建表之前使用 // 当从SQLite中删除数据时,数据文件大小不会减小,当重新插入数据时, // 将使用那块“空白”空间,打开自动清理后,删除数据后,会自动清理“空白”空间 cmd.CommandText = "PRAGMA auto_vacuum = 1"; cmd.ExecuteNonQuery(); // 创建article表 StringBuilder strBuilder = new StringBuilder(); strBuilder.Append("CREATE TABLE article"); strBuilder.Append("("); strBuilder.Append("id INTEGER PRIMARY KEY AUTOINCREMENT,"); strBuilder.Append("category TEXT NOT NULL COLLATE NOCASE,"); strBuilder.Append("title TEXT NOT NULL COLLATE NOCASE,"); strBuilder.Append("content BLOB NOT NULL,"); strBuilder.Append("creationTime TEXT NOT NULL,"); strBuilder.Append("modificationTime TEXT NOT NULL"); strBuilder.Append(")"); cmd.CommandText = strBuilder.ToString(); cmd.ExecuteNonQuery(); // 更改密码 conn.ChangePassword("iSunshine.net@Gmail.com"); // 关闭连接 conn.Close(); } /// <summary> /// 判断数据文件是否正常 /// </summary> /// <param name="filePath">文件路径</param> /// <returns>正常则返回true</returns> public static bool IsDbFileCorrect(string filePath) { SQLiteConnection conn = new SQLiteConnection("Data Source=" + filePath + ";Password="); bool canOpen = false; try { conn.Open(); // 尝试打开链接,发生异常则说明数据库文件损坏 SQLiteCommand cmd = conn.CreateCommand(); cmd.CommandType = CommandType.Text; cmd.CommandText = "PRAGMA table_info(article)"; // 尝试查询表信息,发生异常则说明数据库文件损坏 SQLiteDataReader dataReader = cmd.ExecuteReader(CommandBehavior.CloseConnection); if (dataReader.Read()) { canOpen = true; } dataReader.Close(); } catch { canOpen = false; } return canOpen; }