A Basic SQLite DAL class in C#
You have to first download ADO.Net provider for SQLite from here and use it’s reference in your project.
The class has enough functions for basic DAL operations but you are free to enhance it as per your need.
public static class SqliteDal
{
public static string cnstr = "Data Source =" + "yourdb.db3";
/// <summary>
/// Returns datatbale for given sql query.
/// </summary>
/// <param name="sql"></param>
/// <returns></returns>
public static DataTable getData(string sql)
{
SQLiteConnection cn = new SQLiteConnection(cnstr);
cn.Open();
try
{
SQLiteCommand cm = new SQLiteCommand(sql, cn);
SQLiteDataReader dr = cm.ExecuteReader();
DataTable dt = new DataTable();
dt.Load(dr);
cn.Close();
return dt;
}
catch (Exception ex)
{
cn.Close();
throw ex;
}
}
/// <summary>
/// Returns count of executed insert, update, delete statement.
/// </summary>
/// <param name="sql"></param>
/// <returns></returns>
public static int execNQ(string sql)
{
SQLiteConnection cn = new SQLiteConnection(cnstr);
cn.Open();
SQLiteCommand cm = new SQLiteCommand(sql, cn);
int rows;
rows = cm.ExecuteNonQuery();
cn.Close();
return rows;
}
/// <summary>
/// Returns scalar for given sql query.
/// </summary>
/// <param name="sql"></param>
/// <returns></returns>
public static object execSC(string sql)
{
SQLiteConnection cn = new SQLiteConnection(cnstr);
cn.Open();
SQLiteCommand cm = new SQLiteCommand(sql, cn);
object rows;
rows = cm.ExecuteScalar();
cn.Close();
if (rows == null)
{
rows = 0;
}
return rows;
}
}