Android在SQLite数据库的操作分为查询、添加、删除、修改了,下面我为大家分享的是一个关于Android SQLite数据库操作类的示例:
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
public class DatabaseHelper extends SQLiteOpenHelper {
private static final String DB_NAME = "myDatabase.db"; //数据库名称
private static final int DB_VERSION = 1; //数据库版本
public DatabaseHelper(Context context) {
super(context, DB_NAME, null, DB_VERSION);
}
@Override
public void onCreate(SQLiteDatabase db) {
// 创建数据表
String sql = "create table user(" +
"id integer primary key autoincrement, " +
"name varchar(20), " +
"age integer)";
db.execSQL(sql);
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// 数据库升级时执行的操作
if (oldVersion < newVersion) {
String sql = "DROP TABLE IF EXISTS user";
db.execSQL(sql);
onCreate(db);
}
}
public void addUser(String name, int age) {
SQLiteDatabase db = getWritableDatabase();
String sql = "insert into user(name, age) values(?,?)";
db.execSQL(sql, new Object[]{name, age});
db.close();
}
public void deleteUser(String name) {
SQLiteDatabase db = getWritableDatabase();
String sql = "delete from user where name=?";
db.execSQL(sql, new Object[]{name});
db.close();
}
public void updateUser(String name, int newAge) {
SQLiteDatabase db = getWritableDatabase();
String sql = "update user set age=? where name=?";
db.execSQL(sql, new Object[]{newAge, name});
db.close();
}
public void queryUser(String name) {
SQLiteDatabase db = getReadableDatabase();
String sql = "select * from user where name=?";
db.rawQuery(sql, new String[]{name});
db.close();
}
}
你可以使用这个类来方便地操作SQLite数据库。调用addUser
、deleteUser
、updateUser
、和queryUser
方法可以方便地进行增删改查操作。
发布者:luotuoemo,转转请注明出处:https://www.jintuiyun.com/169946.html