介绍
这篇文章给大家介绍Android项目如何实现连接SQLite数据库,内容非常详细,感兴趣的小伙伴们可以参考借鉴,希望对大家能有所帮助。
新建一个Android工程:,
在Src文件夹下新建一个com . example。包databaseHelper:
在这个包中创建两个类,首先我们来看第一个类DatabaseStatic。Java:
包com.example.databaseHelper; 公开课DatabaseStatic { 最后公共静态字符串DATABASE_NAME=癇ookStore.db"; 最后公共静态int DATABASE_VERSION=1; 最后公共静态字符串TABLE_NAME=癰ook"; 最后公共静态字符串BOOK_NAME=癰ookName"; 最后公共静态字符串ID=癬id"; 最后公共静态字符串作者=癮uthor"; 最终的静态字符串价格=皃rice"; 最后公共静态字符串日期=皊ellData"; }
这个类中定义了数据库名称,版本,还有里面有一个名为“书”的表的相关信息,实现我们上面的意图,接下来是这个包里面的另外一个类MyHelper。java:
包com.example.databaseHelper; 进口android.content.Context; 进口android.database.sqlite.SQLiteDatabase; 进口android.database.sqlite.SQLiteDatabase.CursorFactory; 进口android.database.sqlite.SQLiteOpenHelper; 进口android.util.Log; 进口android.widget.Toast;/* *在这个类的构造函数里面我们调用了父类的构造方法用来创建数据库文 *件,第二个构造方法只是为了方便构造(不用些那么多的参数) *这个类继承了SQLiteOpenHelper类,并且重写了父类里面的 onCreate方法和> & lt; LinearLayout xmlns: android=癶ttp://schemas.android.com/apk/res/android" xmlns:工具=癶ttp://schemas.android.com/tools" android: id=癅 + id/mainLayout" android: layout_width=癿atch_parent" android: layout_height=癿atch_parent" android:取向=皏ertical" android:重力=癱enter_horizontal" 工具:上下文=?MainActivity"比; & lt;按钮 android: id=癅 + id/buttonCreateDatabase" android: layout_width=皐rap_content" android: layout_height=皐rap_content" android:文本=按唇ㄊ菘狻?/比; & lt;按钮 android: id=癅 + id/buttonInsertDatabase" android: layout_width=皐rap_content" android: layout_height=皐rap_content" android:文本=安迦胧荨?比; & lt;按钮 android: id=癅 + id/buttonUpdateDatabase" android: layout_width=皐rap_content" android: layout_height=皐rap_content" android:文本=案率荨?比; & lt;按钮 android: id=癅 + id/buttonDeleteDatabase" android: layout_width=皐rap_content" android: layout_height=皐rap_content" android:文本=吧境荨?比; & lt;按钮 android: id=癅 + id/buttonQueryDatabase" android: layout_width=皐rap_content" android: layout_height=皐rap_content" android:文本=跋允臼菘庵惺楸碇械乃惺荨?比; & lt;/LinearLayout>
一段布局代码,主要的是5个按钮对应5中对数据库的操作:创建数据库,插入数据,更新数据,删除数据,显示(查询)数据。
那么最后是MainActivity。java:
进口com.example.databaseHelper.DatabaseStatic; 进口com.example.databaseHelper.MyHelper; 进口android.os.Bundle; 进口android.app.Activity; 进口android.content.ContentValues; 进口android.database.Cursor; 进口android.database.sqlite.SQLiteDatabase; 进口android.graphics.Color; 进口android.view.Menu; 进口android.view.View; 进口android.widget.Button; 进口android.widget.LinearLayout; 进口android.widget.TextView; 进口android.widget.Toast; 公开课MainActivity延伸活动{ 私人MyHelper MyHelper=零; 私人按钮按钮=零; 私人SQLiteDatabase数据库=零; 私有静态int bookSum=0; TextView TextView=零; @Override 保护无效alt=" Android项目如何实现连接SQLite数据库">好了,运行一下: