0% found this document useful (0 votes)
3 views4 pages

SQLite en Android Studio Con Java

The document provides a guide on implementing CRUD operations using SQLite in Android Studio, showcasing examples in both Java and Kotlin. It includes the creation of database tables, insertion, reading, updating, and deletion of records, as well as the use of triggers for auditing. Additionally, it outlines the basic syntax for creating triggers in SQLite for various database events.

Uploaded by

Eric Rivera
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views4 pages

SQLite en Android Studio Con Java

The document provides a guide on implementing CRUD operations using SQLite in Android Studio, showcasing examples in both Java and Kotlin. It includes the creation of database tables, insertion, reading, updating, and deletion of records, as well as the use of triggers for auditing. Additionally, it outlines the basic syntax for creating triggers in SQLite for various database events.

Uploaded by

Eric Rivera
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 4

CRUD de SQLite en Android Studio

Forma 1 (Java)
public class bd extends SQLiteOpenHelper {

private final String sql= "CREATE TABLE USER(ID INTEGER primary key AUTOINCREMENT,NAME TEXT,APELLIDO TEXT, PHONE TEXT)";

public bd(Context context, String name, SQLiteDatabase.CursorFactory factory, int version) {


super(context, name, factory, version);
}

@Override
public void onCreate(SQLiteDatabase db) {
db.execSQL(sql);
}

@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS USER");
onCreate(db);
}
}

Forma 1 usando Trigger(Kotlin)

class BaseDatos(context:Context,name:String,factory:SQLiteDatabase.CursorFactory?, version:Int):


SQLiteOpenHelper(context,name,factory,version) {

override fun onCreate(db: SQLiteDatabase?) {


db!!.execSQL("CREATE TABLE COMPANY(ID INTEGER PRIMARY KEY AUTOINCREMENT,NAME TEXT NOT
NULL,AGE INT NOT NULL,ADDRESS CHAR(50),SALARY REAL)")

db!!.execSQL("CREATE TABLE AUDIT(EMP_ID INTEGER NOT NULL,ENTRY_DATE TEXT NOT NULL)")

//Trigger
db!!.execSQL("CREATE TRIGGER audit_log AFTER INSERT ON COMPANY BEGIN INSERT INTO
AUDIT(EMP_ID, ENTRY_DATE) VALUES (new.ID, datetime('now')); END;")
}

override fun onUpgrade(db: SQLiteDatabase?, oldVersion: Int, newVersion: Int) {

}
}
//Ejecución

CRUD
CRUD crud = new CRUD(this,”bd_Name”,null,num_version);
/*Create*/
SQLiteDatabase db = crud.getWritableDatabase();
ContentValues valores = new ContentValues();
valores.put("name", “nombre”);
valores.put("apellido",”apellidoDatos”);
db.insert(“NOMBRE_TABLA”, null, valores);
db.close();

/*Read*/
SQLiteDatabase db = crud.getReadableDatabase();
String[] args = new String[] {"usu1"};
Cursor c = db.rawQuery(" SELECT * FROM Usuarios WHERE nombre=? ", args);
While(c.moveToNext()){
c.getString(num de columna)
}
c.close();
db.close();

/*Update*/
SQLiteDatabase db = crud.getWritableDatabase();
ContentValues values = new ContentValues();
values.put("nombre",nombre);
int cant = db.update(“NOMBRE_TABLA”, values, "dni="+dni ’(where)’, null);
db.close();

/*Delete*/
SQLiteDatabase bd = crud.getWritableDatabase();
String dni = et1.getText().toString();
// aquí borro la base de datos del usuario por el dni
int cant = bd.delete(“NOMBRE_TABLA”, "dni=" + dni, null);
bd.close();
Forma 2
public class CRUD {
SQLiteDatabase cx;
ArrayList<Contacto> lista = new ArrayList<Contacto>();
Contacto c;
Context ct;
String BdName ="Contactos";
String tabla= "CREATE table if not exists USER(ID INTEGER primary key AUTOINCREMENT,NAME
TEXT,APELLIDO TEXT, PHONE TEXT)";

public CRUD(Context ct) {


this.ct = ct;
cx = ct.openOrCreateDatabase(BdName,Context.MODE_PRIVATE,null);
cx.execSQL(tabla);
}

public boolean CRUD(Contacto c){


ContentValues contentValues= new ContentValues();
contentValues.put("NAME",c.getName());
contentValues.put("APELLIDO",c.getApellido());
contentValues.put("PHONE",c.getPhone());
return (cx.insert("USER",null,contentValues))>0;
}

public boolean delete(int id){


return (cx.delete("USER","ID="+id,null))>0;

}
public boolean update(Contacto c){
ContentValues contentValues= new ContentValues();
contentValues.put("NAME",c.getName());
contentValues.put("APELLIDO",c.getApellido());
contentValues.put("PHONE",c.getPhone());
return (cx.update("USER",contentValues,"ID="+c.getId(),null))>0;
}
public Contacto selectC(int id) {
Cursor cursor = cx.rawQuery("SELECT * FROM USER",null);
cursor.moveToPosition(id);
c= new Contacto(cursor.getInt(0),
cursor.getString(1),
cursor.getString(2),
cursor.getString(3)
);
return this.c;
}
public ArrayList<Contacto> selectAll(){
lista.clear();
Cursor cursor = cx.rawQuery("SELECT * FROM USER",null);
if(cursor != null && cursor.getCount() >0) {
cursor.moveToFirst();
do{
lista.add(new Contacto(cursor.getInt(0),
cursor.getString(1),
cursor.getString(2),
cursor.getString(3)
));
}while(cursor.moveToNext());
}
return lista;
}
}
TRIGGER

La siguiente es la sintaxis básica de crear un disparador:

CREATE TRIGGER trigger_name [BEFORE|AFTER] event_name


ON table_name
BEGIN
-- Trigger logic goes here....
END

event_name podría ser la operación de la base de datos INSERT, DELETE y UPDATE en la tabla
mencionada table_name

sintaxis para crear un desencadenante en una operación de ACTUALIZACIÓN

CREATE TRIGGER trigger_name [BEFORE|AFTER] UPDATE OF column_name


ON table_name
BEGIN
-- Trigger logic goes here....
END;

You might also like