Android App development often requires the assistance of the embedded database sqlite, which can store our necessary application data. Here is an introduction to how to use java connections to read data in sqlite.
The code in this article has been tested by me and is available for reference.
The code is as follows:
DBHelper.java
package com.web.redrain; import android.content.Context; import android.database.sqlite.SQLiteDatabase; import android.database.sqlite.SQLiteOpenHelper; public class DBHelper extends SQLiteOpenHelper { public DBHelper(Context context) { super(context, "user.db", null, 1); //创建user.db数据库 } @Override public void onCreate(SQLiteDatabase db) { db.execSQL("CREATE table IF NOT EXISTS user" + " (_id INTEGER PRIMARY KEY AUTOINCREMENT, id TEXT, name TEXT, img TEXT, isOnline TEXT)");//创建user表 } @Override public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { db.execSQL("ALTER TABLE user ADD COLUMN other TEXT"); } }
Calling method:
DBHelper helper = new DBHelper(getBaseContext()); SQLiteDatabase db = helper.getWritableDatabase(); db.execSQL("delete from user where 1=1"); db.execSQL("insert into user (id,name,img,isOnline) values('我是个人','见人在此','我会乱说','我是神,oh,my god!!!!')"); Cursor c = db.rawQuery("select * from user", null); while (c.moveToNext()) { alert(c.getString(c.getColumnIndex("id"))); alert(c.getString(c.getColumnIndex("name"))); alert(c.getString(c.getColumnIndex("img"))); alert(c.getString(c.getColumnIndex("isOnline"))); }
alert method:
public void alert(String txt){ Toast.makeText(MainActivity.this,txt, 1).show(); }
This article is provided by PHP Chinese website
Article address: http://www.php.cn/java-article-377105.html
To learn programming, come to PHP Chinese website www.php.cn
The above is the detailed content of How to operate the embedded database sqlite in Android development. For more information, please follow other related articles on the PHP Chinese website!