android studio使用SQLiteOpenHelper()建立数据库的方法
在androidstudio中存储数据有三个方法,分别是:
(1)简单存储——SharedPreferences
(2)文件存储:内部存储——应用程序私有文件外部存储——SD卡资源文件——只读(RAW、XML)
(3)数据库存储——SQLiteDataBase
今天我们讲讲在androidstudio中利用数据库存储中的SQLiteOpenHelper()方法建立数据库SQLiteOpenH
elper中需要重载函数:
onCreate():利用SQL语句,在系统中创建数据库(表)功能
onUpgrade():利用SQL语句,在系统中升级数据库(表)功能
注:
onCreate()方法只有第一次数据库创建时会用到onUpgrade()方法在版本更新会用到
SQLiteOpenHelper中被调用的函数:getWritable
Database():获取一个可读写的SQLiteDatabase对象
getReadableDatabase():获取一个只读的SQLiteDatabase对象
创建数据库
1.新建一个类继承SQLiteOpenHelper
这里按Alt+Enter俩次添加构造方法
publicclassMySQLOpenHelperextendsSQLiteOpenHelper{ publicMySQLOpenHelper(@NullableContextcontext,@NullableStringname,@NullableSQLiteDatabase.CursorFactoryfactory,intversion){ super(context,name,factory,version); }
(1)这个方法里面是用来创建数据库的
context是一个访问application环境全局信息的接口,通过它可以访问application的资源和相关的类context其主要功能如下:启动Activity启动和停止Service发送广播消息(Intent)注册广播消息(Intent)接收者可以访问APK中各种资源(如Resources和AssetManager等)可以访问Package的相关信息APK的各种权限管理Context就是一个对APK包无所不知的大管家,大家需要什么,直接问它就可以了(2)name是数据库的名字(3)CursorFactoryfactory游标工厂,用来指向数据库里面的某一行CursorFactory用来创建游标的,默认值为null,指向一开始的位置(4)version数据库的版本号版本号只能增加,不能递减,要不然程序会崩溃
其他俩个方法是用来创建表的,接下来会讲到我们继续构建数据库:在MySQLOpenHelper类中重构代码:
publicclassMySQLOpenHelperextendsSQLiteOpenHelper{ publicMySQLOpenHelper(@NullableContextcontext){//name是数据库名字,后缀加.db super(context,"SQLite.db",null,1); }
在MainActivity类中调用这个方法
MySQLOpenHelperhelper=newMySQLOpenHelper(this);
然后再在MainActivity类中实例化数据库添加代码如下
MySQLOpenHelperhelper=newMySQLOpenHelper(this); //创建一个可读可写的数据库 SQLiteDatabasewritableDatabase=helper.getWritableDatabase(); //创建一个只可读的数据库 SQLiteDatabasereadableDatabase=helper.getReadableDatabase();
这个读者看需要自行构建代码,(只能存在一个)
我们的数据库创建完成了,接下来看看我们的数据库是否创建成功了呢在看之前我们先运行我们的虚拟机,因为数据库是建立在虚拟机里面的,运行完之后我们去找创建的文件。
android3.0以前打开虚拟机中的文件是用导航栏中的Tools中Android,3.0以后为了提供的更新工具把它舍弃了但我们可以通过View导航栏中ToolWindows中的DeviceFileExplorer打开,找到data目录下的data下的程序的包名,找到创建的数据库(.db文件//另一个是相对应的日记文件),右键重新建立目录,然后用SQLiteExpertProfessional打开SQLiteExpertProfessional下载地址:http://www.sqliteexpert.com 找到的文件如图
用SQLiteExpertProfessional打开后如图
说明我们数据库已经创建好了
总结
到此这篇关于androidstudio使用SQLiteOpenHelper()建立数据库的方法的文章就介绍到这了,更多相关androidstudio建立数据库内容请搜索毛票票以前的文章或继续浏览下面的相关文章希望大家以后多多支持毛票票!
声明:本文内容来源于网络,版权归原作者所有,内容由互联网用户自发贡献自行上传,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任。如果您发现有涉嫌版权的内容,欢迎发送邮件至:czq8825#qq.com(发邮件时,请将#更换为@)进行举报,并提供相关证据,一经查实,本站将立刻删除涉嫌侵权内容。