SQLiteDatabase.cs

原创 2016年06月01日 08:52:42
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;
    }

}


内容举报
返回顶部
收藏助手
不良信息举报
您举报文章:SQLiteDatabase.cs
举报原因:
原因补充:

(最多只允许输入30个字)