【问题标题】:Object reference not set to an instance of an object - Select statement Sqlite Xamarin iOS对象引用未设置为对象的实例 - Select 语句 Sqlite Xamarin iOS
【发布时间】:2017-06-24 17:13:17
【问题描述】:

我在我的 iOS 应用程序中从 sqlite 数据库中获取值。我写了一个像 stringquery = "Select * from tablename" 这样的 Select 语句并使用

执行它

database.Query

(stringquery);

并将值分配给类中的属性。该类具有与 sqlite 数据库中的表中的列具有相同名称的属性。

在执行上述语句时,我收到错误对象引用未设置为对象的实例

请提出这个问题的解决方案。

谢谢

【问题讨论】:

  • 你模糊地描述了你在做什么,但从不说问题是什么。
  • @deckertron_9000 如果您阅读标题和说明,您就会知道我在做什么以及有什么问题。但为了您的理解,我正在编辑问题。
  • 抛出异常时,异常说哪个对象为null?
  • 执行代码时database.Query
(stringquery);

标签: ios database sqlite xamarin.ios xamarin.forms


【解决方案1】:

听起来您正在错误地初始化 SQLite 数据库。我在下面添加了代码,展示了如何在 Xamarin.Forms 中实现 SQLite 数据库。

此 Xamarin.Forms 应用包含一个完全实现的 SQLite 数据库: https://github.com/brminnick/InvestmentDataSampleApp

ISQLite.cs

在 Xamarin.Forms PCL 中创建此文件。它允许我们访问 iOS 和 Android 文件系统来创建我们的数据库连接

using SQLite;

namespace SampleApp
{
    public interface ISQLite
    {
        SQLiteAsyncConnection GetConnection();
    }
}

SQLite_Android.cs

在 Android 项目中创建此文件。它返回我们的 SQLite 数据库连接的 Android 文件路径。

using System.IO;

using SampleApp.Droid;

using SQLite;

using Xamarin.Forms;

[assembly: Dependency(typeof(SQLite_Android))]
namespace SampleApp.Droid
{
    public class SQLite_Android : ISQLite
    {
        #region ISQLite implementation
        public SQLiteAsyncConnection GetConnection()
        {
            var sqliteFilename = "DatabaseFileName.db3";
            string documentsPath = System.Environment.GetFolderPath(System.Environment.SpecialFolder.Personal); // Documents folder
            var path = Path.Combine(documentsPath, sqliteFilename);

            var conn = new SQLiteAsyncConnection(path, SQLiteOpenFlags.ReadWrite | SQLiteOpenFlags.Create | SQLiteOpenFlags.SharedCache);

            // Return the database connection 
            return conn;
        }
        #endregion
    }
}

SQLite_iOS.cs

在 iOS 项目中创建此文件。它返回我们的 SQLite 数据库连接的 iOS 文件路径。

using System;
using System.IO;

using SQLite;

using Xamarin.Forms;

using SampleApp.iOS;

[assembly: Dependency(typeof(SQLite_iOS))]
namespace SampleApp.iOS
{
    public class SQLite_iOS : ISQLite
    {
        #region ISQLite implementation
        public SQLiteAsyncConnection GetConnection()
        {
            var sqliteFilename = "DatabaseFileName.db3";
            string documentsPath = Environment.GetFolderPath(Environment.SpecialFolder.Personal); // Documents folder
            string libraryPath = Path.Combine(documentsPath, "..", "Library"); // Library folder
            var path = Path.Combine(libraryPath, sqliteFilename);

            var conn = new SQLiteAsyncConnection(path, SQLiteOpenFlags.ReadWrite | SQLiteOpenFlags.Create | SQLiteOpenFlags.SharedCache);

            // Return the database connection 
            return conn;
        }
        #endregion
    }
}

SampleModelDatabase.cs

在 Xamarin.Forms PCL 中创建此文件

using System.Linq;
using System.Threading.Tasks;
using System.Collections.Generic;

using SQLite;

using Xamarin.Forms;

namespace SampleApp
{
    public static class SampleModelDatabase
    {
        #region Constant Fields
        static readonly SQLiteAsyncConnection _database = DependencyService.Get<ISQLite>().GetConnection();
        #endregion

        #region Fields
        static bool _isInitialized;
        #endregion

        #region Methods

        public static async Task<IList<SampleModel>> GetAllItemsAsync()
        {
            if (!_isInitialized)
                await Initialize();

            return await _database.Table<SampleModel>().ToListAsync();
        }

        public static async Task<int> SaveItemAsync(SampleModel model)
        {
            if (!_isInitialized)
                await Initialize();

            return await _database.InsertOrReplaceAsync(model);
        }

        public static async Task<int> DeleteItemAsync(SampleModel model)
        {
            if (!_isInitialized)
                await Initialize();

            return await _database.DeleteAsync(model);
        }

        public static async Task<int> GetNumberOfRowsAsync()
        {
            if (!_isInitialized)
                await Initialize();

            return await _database.Table<SampleModel>().CountAsync();
        }

        static async Task Initialize()
        {
            await _database.CreateTableAsync<SampleModel>();
            _isInitialized = true;
        }
        #endregion
    }
}

【讨论】:

  • 感谢您的 cmets。这看起来像是我在其他地方看到的东西,所以让我问一下……您提供的代码/方法是使用“sqlite-net-pcl”还是使用“microsoft.entityframeworkcore.sqlite”nuget 包?我问的原因是 1)我正在尝试使用 Microsoft 的,2)没有示例使用“连接”对象显示它,并且自动完成点符号中没有“表格”,如您所示在这里。
  • 嗨@唐娜!这使用 sqlite-net-pcl:nuget.org/packages/sqlite-net-pcl
【解决方案2】:

我遇到了和你一样的问题。我发现关键是数据库连接,一个需要时间的过程,在我开始查询时还没有完全完成。所以解决方案是这样的:

await Connectdb();
// now do your query
var treatment = _database.Query<ClassName>("SELECT * FROM [TableName] WHERE ...");

Connectdb() 是一个函数:

DependencyService.Get<IDatabaseConnection>().DbConnection();

【讨论】:

    猜你喜欢
    相关资源
    最近更新 更多
    热门标签