📜  在片段中访问数据库 - Java 代码示例

📅  最后修改于: 2022-03-11 14:52:39.308000             🧑  作者: Mango

代码示例1
public class DatabaseHelper extends SQLiteOpenHelper {

public static final String DATABASE_NAME = "hunderassen.db";
public static final String TABLE_NAME = "hunderassen_table";
public static final String COLUMN1 = "ID";
public static final String COLUMN2 = "name_Hunderasse";
public static final String COLUMN3 = "durchschnittlicheDauer";
public static final String COLUMN4 = "groesseHund";


public DatabaseHelper(Context context) {
    super(context, DATABASE_NAME, null, 1); //creating db and table
}

@Override
public void onCreate(SQLiteDatabase db) {
    db.execSQL("create table " + TABLE_NAME + " (ID INTEGER PRIMARY KEY AUTOINCREMENT, name_Hunderasse TEXT, durchschnittlicheDauer TEXT, groesseHund TEXT) ");
}

@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
    db.execSQL("drop table if exists " + TABLE_NAME);
    this.onCreate(db);
}

public boolean insertData(String name_hr, String durchschnitt, String groesse) {

    SQLiteDatabase database = this.getWritableDatabase();

    ContentValues contentValues = new ContentValues();
    contentValues.put(COLUMN2, name_hr);
    contentValues.put(COLUMN3, durchschnitt);
    contentValues.put(COLUMN4, groesse);
    long result = database.insert(TABLE_NAME, null, contentValues);

    //check if value is -1
    if (result == -1) {
        return false;
    } else {
        return true;
    }
}