Notice
Recent Posts
Recent Comments
Link
일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
1 | ||||||
2 | 3 | 4 | 5 | 6 | 7 | 8 |
9 | 10 | 11 | 12 | 13 | 14 | 15 |
16 | 17 | 18 | 19 | 20 | 21 | 22 |
23 | 24 | 25 | 26 | 27 | 28 |
Tags
- 코틀린
- 랜덤넘버
- 안드로이드
- fragment
- 자바스크립트
- JS
- nodejs
- 랜덤번호
- Java
- array
- SpringBoot
- TextView
- button
- stylesheet
- Javscript
- Android
- scrollview
- 리액트
- RecyclerView
- npm
- 스프링부트
- 오버라이딩
- GoogleMaps
- Linux
- JavaScript
- 구글맵스
- React
- Hook
- TypeScript
- Kotlin
Archives
- Today
- Total
타닥타닥 개발자의 일상
kotlin 코틀린 sqllite로 데이터 입력,삭제,조회하는 안드로이드 프로그램 만들기 본문
sqlite는 MySQL처럼 외부에 있는 데이터가 아니라 Android 내부에 저장된 자료이다.
폴더 및 파일구성
com.example.sample36 폴더에 DBHelper 클래스 만들기
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity" >
<EditText
android:layout_width="527dp"
android:layout_height="67dp"
android:inputType="textPersonName"
android:ems="10"
android:id="@+id/editInsert"
android:hint="추가하거나 조회할 값을 입력하시오"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintHorizontal_bias="0.506"
app:layout_constraintVertical_bias="0.048"/>
<TextView
android:id="@+id/textView"
android:text="조회된 자료"
android:layout_width="522dp"
android:layout_height="67dp"
app:layout_constraintTop_toBottomOf="@+id/editInsert"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintVertical_bias="0.031"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"/>
<Button
android:text="추가"
android:layout_width="298dp"
android:layout_height="46dp"
android:id="@+id/insertBtn"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
android:layout_marginBottom="504dp"
app:layout_constraintTop_toBottomOf="@+id/textView"
app:layout_constraintVertical_bias="0.966" app:layout_constraintHorizontal_bias="0.493"/>
<Button
android:text="검색"
android:layout_width="298dp"
android:layout_height="46dp"
android:id="@+id/selectBtn"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintBottom_toBottomOf="parent"
android:layout_marginBottom="340dp"
app:layout_constraintTop_toBottomOf="@+id/insertBtn"
app:layout_constraintVertical_bias="0.407" app:layout_constraintHorizontal_bias="0.493"/>
<Button
android:text="삭제"
android:layout_width="298dp"
android:layout_height="46dp"
android:id="@+id/deleteBtn"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintTop_toBottomOf="@+id/insertBtn"
app:layout_constraintVertical_bias="0.32"/>
</androidx.constraintlayout.widget.ConstraintLayout>
DBHelper.kt
package com.example.sample36
import android.content.Context
import android.database.sqlite.SQLiteDatabase
import android.database.sqlite.SQLiteOpenHelper
class DBHelper(context: Context?,name:String?,factory:SQLiteDatabase.CursorFactory?,version: Int)
: SQLiteOpenHelper(context,name,factory,version) {
//매개변수는 DB instance
override fun onCreate(db: SQLiteDatabase?) {
//쿼리문. 존재하지 않는다면 테이블을 생성하라는 말
//시퀀스
//컬럼명
var sql : String = " CREATE TABLE IF NOT EXISTS MYTABLE( " +
" SEQ INTEGER PRIMARY KEY AUTOINCREMENT, " +
" TXT TEXT) "
db?.execSQL(sql)
}
override fun onUpgrade(db: SQLiteDatabase?, oldVersion: Int, newVersion: Int) {
var sql : String = " DROP TABLE IF EXISTS MYTABLE "
db?.execSQL(sql)
onCreate(db)
}
fun insert(db: SQLiteDatabase,txt:String){
var sql = " INSERT INTO MYTABLE(TXT) " +
" VALUES('${txt}')"
db.execSQL(sql)
}
fun select(db: SQLiteDatabase, txt:String) : String?{
var sql = " SELECT * FROM MYTABLE " +
" WHERE TXT='${txt}' "
var result = db.rawQuery(sql, null)
var str:String? = ""
while (result.moveToNext()){
str += "번호 :" +result.getString(result.getColumnIndex("SEQ")) + "\n" +
"데이터 :" + result.getString(result.getColumnIndex("TXT"))
}
return str
}
fun delete(db:SQLiteDatabase,txt:String){
val sql = " DELETE FROM MYTABLE " +
" WHERE TXT='${txt}' "
db.execSQL(sql)
}
}
MainActivity.kt
package com.example.sample36
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.widget.Button
import android.widget.EditText
import android.widget.TextView
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
var dbHelper = DBHelper(this, "mydb.db",null,1)
val insertBtn = findViewById<Button>(R.id.insertBtn) //자료 입력
val editInsert = findViewById<EditText>(R.id.editInsert) //입력 혹은 검색
val selectBtn = findViewById<Button>(R.id.selectBtn) // 자료 조회
val deleteBtn = findViewById<Button>(R.id.deleteBtn) // 자료 삭제
val textView = findViewById<TextView>(R.id.textView) //검색자료 표시
var database = dbHelper.writableDatabase
insertBtn.setOnClickListener {
//입력받은 내용 불러오기
val txt = editInsert.text
//insert함수 호출
val result = dbHelper.insert(database,txt.toString())
if(result!=null){
textView.text = "입력한 데이터 ${txt}가 저장되었습니다."
}
else{
textView.text ="데이터가 입력되지 않았습니다."
}
}
selectBtn.setOnClickListener {
val txt = editInsert.text
textView.text =dbHelper.select(database,txt.toString())
}
deleteBtn.setOnClickListener {
val txt =editInsert.text
//delete 함수 호출
val result = dbHelper.delete(database,txt.toString())
if(result!=null){
textView.text = "데이터값 ${txt}가 삭제 됐습니다."
}
else{
textView.text ="데이터가 입력되지 않았습니다."
}
}
}
}
Device File Explorer 선택 > data > 해당하는 폴더 클릭 > databases 폴더 > mydb.db 파일에 데이터가 저장되어있다.
mydb.db파일을 보거나 실행하기 위해서는 SQLite라는 프로그램이 필요하다.
SQLite은 아래에서 다운로드 가능
실행화면
'코딩 기록 > Kotlin' 카테고리의 다른 글
Comments