95 lines
3.6 KiB
C#
95 lines
3.6 KiB
C#
using Microsoft.Data.Sqlite;
|
|
using System;
|
|
using System.IO;
|
|
|
|
namespace AvaloniaLinuxForm
|
|
{
|
|
public class SQLiteUtil
|
|
{
|
|
public static string appDataPath = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData);
|
|
public static string dbFolderPath = Path.Combine(appDataPath, "SygAvalonia");
|
|
public static string dbFilePath = Path.Combine(dbFolderPath, "database.sqlite");
|
|
|
|
public static void InitDatabase()
|
|
{
|
|
try
|
|
{
|
|
if (!Directory.Exists(dbFolderPath))
|
|
{
|
|
Directory.CreateDirectory(dbFolderPath);
|
|
}
|
|
// 创建数据库连接(如果文件不存在,会自动创建)
|
|
using (SqliteConnection connection = new SqliteConnection($"Data Source={dbFilePath};"))
|
|
{
|
|
connection.Open();
|
|
|
|
// 初始化系统配置表结构
|
|
string createTableQuery = @"
|
|
CREATE TABLE IF NOT EXISTS program_config (
|
|
Id INTEGER PRIMARY KEY AUTOINCREMENT,
|
|
Url TEXT NOT NULL
|
|
);";
|
|
using (SqliteCommand command = new SqliteCommand(createTableQuery, connection))
|
|
{
|
|
int result = command.ExecuteNonQuery();
|
|
string configCountQuery = @"select count(0) from program_config;";
|
|
using (SqliteCommand configCountCommand = new SqliteCommand(configCountQuery, connection))
|
|
using (SqliteDataReader reader = configCountCommand.ExecuteReader())
|
|
{
|
|
while (reader.Read())
|
|
{
|
|
int configCount = reader.GetInt32(0);
|
|
if (configCount == 0)
|
|
{
|
|
// 初始化系统配置数据
|
|
string initConfigDataQuery = @"insert into program_config (Url) values('https://www.baidu.com');";
|
|
using (SqliteCommand dataCommand = new SqliteCommand(initConfigDataQuery, connection))
|
|
{
|
|
dataCommand.ExecuteNonQuery();
|
|
}
|
|
}
|
|
}
|
|
}
|
|
}
|
|
connection.Close();
|
|
}
|
|
}
|
|
catch (Exception ex)
|
|
{
|
|
Console.WriteLine("数据库初始化失败:" + ex.Message);
|
|
}
|
|
}
|
|
|
|
// 保存url
|
|
public static void SaveUrl(string url)
|
|
{
|
|
using var connection = new SqliteConnection($"Data Source={dbFilePath}");
|
|
connection.Open();
|
|
var cmd = connection.CreateCommand();
|
|
cmd.CommandText = "update program_config set Url = $Url where id = '1'";
|
|
cmd.Parameters.AddWithValue("$Url", url);
|
|
cmd.ExecuteNonQuery();
|
|
connection.Close();
|
|
}
|
|
|
|
// 加载保存的url
|
|
public static string LoadUrl()
|
|
{
|
|
using var connection = new SqliteConnection($"Data Source={dbFilePath}");
|
|
connection.Open();
|
|
|
|
var cmd = connection.CreateCommand();
|
|
cmd.CommandText = "SELECT Url FROM program_config where id='1'";
|
|
|
|
using var reader = cmd.ExecuteReader();
|
|
if (reader.Read())
|
|
{
|
|
return reader.GetString(0);
|
|
}
|
|
return null;
|
|
}
|
|
|
|
|
|
}
|
|
}
|