gpt4 book ai didi

c# - 使用 Xamarin Forms,如何在共享代码中创建我的 SQLite 连接?

转载 作者:行者123 更新时间:2023-12-03 16:01:28 24 4
gpt4 key购买 nike

我最近注意到几篇文章提到在通用代码中创建 SQLite 连接。这是新的东西,因为我一直用这样的界面来做:
有没有一种方法可以在通用代码中完成这一切,而不是在下面需要通用、iOS 和 Android 代码的实现中完成?
常用代码:

namespace Memorise
{
public interface ISQLiteDB1
{
(SQLiteConnection, bool) GetConnection();
}
}
IOS代码:
[assembly: Dependency(typeof(ISQLiteDB_iOS))]
namespace Memorise.iOS
{
public class ISQLiteDB_iOS : ISQLiteDB
{
public (SQLite.SQLiteConnection, bool) GetConnection(string _dbName)
{
bool newDb = false ;
var sqliteFilename = _dbName;
string documentsPath = Environment.GetFolderPath(Environment.SpecialFolder.Personal);
string libraryPath = Path.Combine(documentsPath, "..", "Library");

Debug.WriteLine(documentsPath);
Debug.WriteLine(libraryPath);

var path = Path.Combine(libraryPath, sqliteFilename);
switch (_dbName)
{
case CONST.DB1Name:
if (File.Exists(path))
{
newDb = false;
File.Delete(path);
}
else
{
newDb = true;
}
File.Copy(sqliteFilename, path);

break;
case CONST.DB2Name:
if (File.Exists(path))
{
newDb = false;
}
else
{
newDb = true;
File.Create(path);
}

break;
case CONST.DB3Name:
if (File.Exists(path))
{
newDb = false;
}
else
{
newDb = true;
File.Copy(sqliteFilename, path);
}
break;
}

return (new SQLite.SQLiteConnection(path), newDb);
}
}
}
安卓代码:
[assembly: Dependency(typeof(SQLiteDB1_Android))]

namespace Memorise.Droid
{
public class SQLiteDB1_Android : ISQLiteDB1
{
public (SQLite.SQLiteConnection, bool) GetConnection()
{
bool newDb;
var sqliteFilename = "db1.db3";
string documentsPath = Environment.GetFolderPath(Environment.SpecialFolder.Personal); // Documents folder
var path = Path.Combine(documentsPath, sqliteFilename);
if (File.Exists(path))
{
newDb = false;
File.Delete(path);
}
else
{
newDb = true;
}
FileStream writeStream = new FileStream(path, FileMode.OpenOrCreate, FileAccess.Write);
ReadWriteStream(Android.App.Application.Context.Assets.Open(sqliteFilename), writeStream);
return (new SQLite.SQLiteConnection(path), newDb);
}

void ReadWriteStream(Stream readStream, Stream writeStream)
{
int Length = 256;
Byte[] buffer = new Byte[Length];
int bytesRead = readStream.Read(buffer, 0, Length);
while (bytesRead > 0)
{
writeStream.Write(buffer, 0, bytesRead);
bytesRead = readStream.Read(buffer, 0, Length);
}
readStream.Close();
writeStream.Close();
}
}
}

最佳答案

我们可以利用 FileSystem Xamarin.Essentials NuGet Package中的API找到特定于平台的应用程序数据目录并在共享代码中创建我们的数据库连接。

var databasePath = Path.Combine(FileSystem.AppDataDirectory, "Database.db3");
var databaseConnection = new SQLiteConnection(databasePath);
我在这篇关于 Xamarin + SQLite 的博文中更深入: https://codetraveler.io/2019/11/26/efficiently-initializing-sqlite-database/

关于c# - 使用 Xamarin Forms,如何在共享代码中创建我的 SQLite 连接?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64329742/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com