初次接触Xamarin.android,尝试开发一个APK,其实入门的教程在微软官方有一大部分,不过关于数据库这块还是看得不知所云

android自带sqlite数据库模块,但是这个引用Visual Studio 2019中好像是没有的(还是我没找到?)

NuGet中下载Mono.Data.Sqlite.Portable安装即可

本来以为很简单的操作,其实不然,下面写个类连接数据库:

public class clsSqlite
    {
        private SqliteConnection m_dbConnection;

        public clsSqlite()
        {
            string dbPath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Personal),"data.db");
            m_dbConnection = new SqliteConnection(string.Format("Data Source={0};Version=3;",dbPath));
            m_dbConnection.Open();
        }
        public bool test()
        {
            string sql = "select count(id) from [login]";
            try
            {
                SqliteCommand command = new SqliteCommand(sql, m_dbConnection);
                object obj = command.ExecuteScalar();
                return true;
            }
            catch(Exception ex) {
                return false;
            }

        }
        public void Close()
        {
            m_dbConnection.Close();
        }
}

因为dbPath输出的是类似路径,这个路径应该就是SD的目录

/data/user/0/com.companyname.app6/files/data.db

所以我在工程目录新建了files目录,把data.db放了进去,但是提示找不到数据表

后来百度一番,好像是要把数据库复制到SD目录 

private void dbImport()
        {
            string dbPath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Personal), "data.db");
            try
            {
                if (!File.Exists(dbPath))//不存在,拷贝raw中的data.db到SD卡目录 
                {
                    Stream stm = Resources.OpenRawResource(Resource.Raw.data);
                    FileStream outfile = new FileStream(dbPath, FileMode.OpenOrCreate, FileAccess.Write);
                    byte[] buffer = new byte[1024];
                    int count = 0;
                    while ((count = stm.Read(buffer)) > 0)
                    {
                        outfile.Write(buffer, 0, count);
                    }
                    outfile.Close();
                    stm.Close();
                }
                //else
                //    File.Delete(dbPath);
            }
            catch (Exception e)
            {
                Toast.MakeText(ApplicationContext.ApplicationContext,"复制数据库失败",ToastLength.Short);
            }
        }

这里需要注意,如果你已经运行过连接数据库文件的操作,但SD文件不存在,Android会默认生成一个空的数据库文件,所以可以先检测一下文件是否存在,如果存在,先把原来的空数据库文件删除

 

Logo

为开发者提供学习成长、分享交流、生态实践、资源工具等服务,帮助开发者快速成长。

更多推荐