关闭

SQLiteDatabase.cs

238人阅读 评论(0) 收藏 举报
分类:
using System;
using System.Data;// DataTable
using System.Data.SQLite;
using System.IO;

// SQLiteConnection,SQLiteCommand,SQLiteDataReader

/// <summary>
/// SQLiteDatabase 的摘要说明
/// </summary>
public class SQLiteDatabase
{
    #region 变量
    private SQLiteConnection _dbConnection;

    #endregion

    #region 属性
    public string FileName { get; set; }
    public string DataSource => $"Data Source={FileName};Version=3;";

    #endregion

    #region 实例化
    private static SQLiteDatabase _instance;
    public static SQLiteDatabase Instance => _instance ?? (_instance = new SQLiteDatabase());
    public SQLiteDatabase()
    {
        FileName = "SQLite.s3db";
    }
    public SQLiteDatabase(string fileName)
    {
        FileName = fileName;
    }

    #endregion

    public void Open()
    {
        if (!File.Exists(FileName)) SQLiteConnection.CreateFile(FileName);
        _dbConnection = new SQLiteConnection(DataSource);
        _dbConnection.Open();
    }

    public void Close()
    {
        _dbConnection.Close();
    }

    public DataTable GetDataTable(string sql)
    {
        var dt = new DataTable();
        try
        {
            var cmd = new SQLiteCommand(_dbConnection) { CommandText = sql };
            var dr = cmd.ExecuteReader();
            dt.Load(dr);
            dr.Close();
        }
        catch
        {
            // ignored
        }
        return dt;
    }

    public int Perform(string sql)
    {
        var result = -1;
        try
        {
            var cmd = new SQLiteCommand(_dbConnection) { CommandText = sql };
            result = cmd.ExecuteNonQuery();
        }
        catch
        {
            // ignored
        }
        return result;
    }

    public bool Perform(string sql, out string err)
    {
        var result = false;
        err = null;
        try
        {
            var cmd = new SQLiteCommand(_dbConnection) { CommandText = sql };
            cmd.ExecuteNonQuery();
            result = true;
        }
        catch (Exception ex)
        {
            err = ex.Message;
        }
        return result;
    }

    public string Query(string sql)
    {
        string result = null;
        try
        {
            var cmd = new SQLiteCommand(_dbConnection) { CommandText = sql };
            result = cmd.ExecuteScalar().ToString();
        }
        catch
        {
            // ignored
        }
        return result;
    }

}


1
0

查看评论
* 以上用户言论只代表其个人观点,不代表CSDN网站的观点或立场
    个人资料
    • 访问:87300次
    • 积分:2038
    • 等级:
    • 排名:第19792名
    • 原创:112篇
    • 转载:3篇
    • 译文:0篇
    • 评论:6条
    文章分类
    最新评论