....
DataDbHelper dh;
String someThing = "test";
try{
dh = new DataDbHelper(Main.this);
dh.insertExample(someThing);
dh.closeDb();
}
catch(Exception e){
//something
}
....
public class DataDbHelper {
private SQLiteDatabase db;
private SQLiteStatement insertStmt;
private static final String TABLE_EXAMPLE = "tbl_example";
private static final String FIELD_CODE_ID = "id";
private static final String FIELD_EXAMPLE = "fld_example";
private static final String INSERT_SQL = "insert into "
+ TABLE_EXAMPLE + " ("+FIELD_EXAMPLE+") values (?)";
public DataDbHelper(Context context) {
this.context = context;
OpenHelper openHelper = new OpenHelper(this.context);
this.db = openHelper.getWritableDatabase();
}
public void insertExample(String someThing) {
try {
this.insertStmt = this.db.compileStatement(INSERT_SQL);
this.insertStmt.bindString(1, someThing);
this.insertStmt.executeInsert();
}
catch(Exception e){}
finally {
if (this.insertStmt !=null) this.insertStmt.close();
}
}
private static class OpenHelper extends SQLiteOpenHelper {
OpenHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
public void onCreate(SQLiteDatabase db) {
db.execSQL("CREATE TABLE " + TABLE_EXAMPLE+
" ("+FIELD_CODE_ID+" INTEGER PRIMARY KEY, "+
FIELD_EXAMPLE+" TEXT)");
}
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
try{
//something
}catch(SQLException e){
//something
}
}
}
}
Sorgenti, linguaggi, best practice, suggerimenti, sul mondo della programmazione e non solo
giovedì 21 giugno 2012
Inserimento dati su db
Questo esempio rappresenta l'inserimento del valore "test" all'interno della tabella "tbl_example" tramite classi java su android.