Skip to content

Instantly share code, notes, and snippets.

@nodoid
Created January 9, 2021 13:01
Show Gist options
  • Save nodoid/b51207dab96c9e24f23ea1403e2cd8bf to your computer and use it in GitHub Desktop.
Save nodoid/b51207dab96c9e24f23ea1403e2cd8bf to your computer and use it in GitHub Desktop.
Getting the connection string for SQLite
Android:
[assembly: Dependency(typeof(SQLConnection))]
namespace MyProject.Droid
{
public class SQLConnection : ISqliteConnectionFactory
{
readonly string Filename = "db_name.db";
public SQLiteConnection GetConnection()
{
var path = Environment.GetFolderPath(Environment.SpecialFolder.Personal);
path = Path.Combine(path, Filename);
var connection = new SQLiteConnection(path, SQLiteOpenFlags.ReadWrite | SQLiteOpenFlags.Create);
return connection;
}
}
}
iOS:
[assembly: Dependency(typeof(SQLiteConnectionFactory))]
namespace MyProject.iOS
{
public class SQLiteConnectionFactory : ISqliteConnectionFactory
{
readonly string Filename = "db_name.db";
public SQLiteConnection GetConnection()
{
var path = Environment.GetFolderPath(Environment.SpecialFolder.Personal);
path = Path.Combine(path, Filename);
return new SQLiteConnection(path, SQLiteOpenFlags.Create | SQLiteOpenFlags.ReadWrite);
}
}
}
Shared:
namespace NyProject.Interfaces
{
public interface ISqliteConnectionFactory
{
SQLiteConnection GetConnection();
}
}
namespace MyProject.Interfaces
{
public interface IRepository
{
void SaveData<T>(T toStore);
void SaveListData<T>(List<T> toStore);
List<T> GetList<T>(int top = 0) where T : class, new();
List<T> GetList<T, TU>(string para, TU val, int top = 0) where T : class, new();
T GetData<T>() where T : class, new();
T GetData<T, TU>(string para, TU val) where T : class, new();
T GetData<T, TU, TV>(string para1, TU val1, string para2, TV val2) where T : class, new();
void Delete<T>(T stored);
void DeleteList<T>(List<T> list);
int GetID<T>() where T : class, new();
int Count<T>() where T : class, new();
int Count<T, U>(string p, U val) where T : class, new();
void DeleteAll();
}
}
namespace MyProject.Database
{
public class SqLiteRepository : IRepository
{
readonly SQLiteConnection connection;
readonly object dbLock;
public SqLiteRepository(ISqliteConnectionFactory connectionFactory)
{
connection = connectionFactory.GetConnection();
CreateTables();
dbLock = new object();
}
public void SaveData<T>(T toStore)
{
try
{
lock (dbLock)
{
connection.InsertOrReplace(toStore);
}
}
catch (Exception ex)
{
#if DEBUG
Debug.WriteLine(ex.Message);
#endif
}
}
... other code
}
App.xaml.cs
Add the DI code here to call the SQLConnection code on the platform
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment