Last active
July 4, 2021 23:58
-
-
Save nunomazer/979ff11b831204d5f718c5a3bbfa305a to your computer and use it in GitHub Desktop.
Classes exemplo de manipulação de banco de dados SQLite com Kotlin
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* Conjunto de arquivos com exemplos de uso do SQLite em Kotlin | |
**/ |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
private const val SQL_CREATE_ENTRIES = | |
"CREATE TABLE ${NotaEntry.TABLE_NAME} (" + | |
"${BaseColumns._ID} INTEGER PRIMARY KEY," + | |
"${NotaEntry.COLUMN_NAME_TITULO} TEXT," + | |
"${NotaEntry.COLUMN_NAME_DESCRICAO} TEXT)" | |
private const val SQL_DELETE_ENTRIES = "DROP TABLE IF EXISTS ${NotaEntry.TABLE_NAME}" |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
val dbHelper = NotaDbHelper(context) |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Acessa o banco de dados em modo de gravação | |
val db = dbHelper.writableDatabase | |
// Cria um novo mapa de valores, onde os nomes das colunas da tabela | |
// são as chaves do mapa (chave:valor) | |
val notaMap = ContentValues().apply { | |
put(NotaEntry.COLUMN_NAME_TITULO, "Compras da padaria") | |
put(NotaEntry.COLUMN_NAME_DESCRICAO, "Comprar leite, pão e manteiga") | |
} | |
// Inserir o novo registro/entidade, o valor da chave primária | |
// é retornado como resultado da execução do método insert | |
val notaId = db?.insert(NotaEntry.TABLE_NAME, null, notaMap) |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class NotaDbHelper(context: Context) : SQLiteOpenHelper(context, DATABASE_NAME, null, DATABASE_VERSION) { | |
override fun onCreate(db: SQLiteDatabase) { | |
db.execSQL(SQL_CREATE_ENTRIES) | |
} | |
override fun onUpgrade(db: SQLiteDatabase, oldVersion: Int, newVersion: Int) { | |
// Este banco de dados guarda apenas notas temporárias, não seria comum mas | |
// por demonstração, neste exemplo, ele exclui os registros e então atualiza o esquema | |
// do banco de dados | |
db.execSQL(SQL_DELETE_ENTRIES) | |
onCreate(db) | |
} | |
override fun onDowngrade(db: SQLiteDatabase, oldVersion: Int, newVersion: Int) { | |
onUpgrade(db, oldVersion, newVersion) | |
} | |
companion object { | |
// Se o esquema do banco mudar você deve alterar a versão. | |
const val DATABASE_VERSION = 1 | |
// Nome do arquivo SQLite em disco | |
const val DATABASE_NAME = "Notas.db" | |
} | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
object NotaContract { | |
// Os conteúdos são agrupados em um objeto anônimo | |
object NotaEntry : BaseColumns { | |
const val TABLE_NAME = "nota" | |
const val COLUMN_NAME_TITULO = "titulo" | |
const val COLUMN_NAME_DESCRICAO = "descricao" | |
} | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Solicita acesso de leitura apenas | |
val db = dbHelper.readableDatabase | |
// Define as colunas que deseja usar da tabela | |
val select = arrayOf(BaseColumns._ID, NotaEntry.COLUMN_NAME_TITULO, NotaEntry.COLUMN_NAME_DESCRICAO) | |
// Filtra os resultados usando WHERE que retornem as notas com ID maior que 10 | |
val filtro = "${BaseColumns._ID} > ?" | |
val argumento = arrayOf(10) | |
// Define a ordenação do resultado | |
val ordem = "${NotaEntry.COLUMN_NAME_TITULO} ASC" | |
val cursor = db.query( | |
NotaEntry.TABLE_NAME, // Nome da tabela | |
select, // Array com os nomes dos campos a serem retornados | |
filtro, // Filtro para cláusula WHERE | |
argumento, // Argumento para o filtro | |
null, // não agrupar os registros | |
null, // não filtrar por grupos | |
ordem // Ordenar | |
) | |
with(cursor) { | |
while (moveToNext()) { | |
println(getString(getColumnIndexOrThrow(NotaFeed.COLUMN_NAME_TITULO)) | |
println(getString(getColumnIndexOrThrow(NotaFeed.COLUMN_NAME_TITULO)) | |
} | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Acesso de gravação | |
val db = dbHelper.writableDatabase | |
// O novo valor da coluna titulo | |
val titulo = "NÃO ESQUECER da padaria" | |
// vamos criar o mapa apenas para o campo a ser alterado | |
val notaMap = ContentValues().apply { | |
put(NotaEntry.COLUMN_NAME_TITULO, titulo) | |
} | |
// Filtro a ser empregado para escolher o registro correto | |
// a ser alterado | |
val filtro = "${NotaEntry.COLUMN_NAME_TITULO} LIKE ?" | |
val argumento = arrayOf("padaria") | |
val count = db.update( | |
NotaEntry.TABLE_NAME, | |
notaMap, | |
filtro, | |
argumento) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment