华域联盟 Andriod Android Kotlin使用SQLite案例详解

Android Kotlin使用SQLite案例详解

文章目录[隐藏]

Kotlin使用SQLite

首先确定我们的目标,SQLite只是一种工具,我们需要掌握就是增删改查就可以,我们真正需要动脑的还是项目中的业务逻辑。我这篇文章写得比较适合新手,没用过SQLite的同学。
前期准备工作
新建一个类MyDataBaseHelper继承自SQLiteOpenHelper,代码如下:

class MyDatabaseHelper(var context: Context, name: String, version: Int) :
    SQLiteOpenHelper(context, name, null, version) {
    public var createBook="create table Book (" +
            "id integer primary key autoincrement," +
            "author text," +
            "price real," +
            "pages integer," +
            "name text)"

    override fun onCreate(db: SQLiteDatabase?) {
//        下面这个todo 如果不注释掉的话就会报错。
//        TODO("not implemented") //To change body of created functions use File | Settings | File Templates.
        db?.execSQL(createBook)
        Toast.makeText(context,"Create Successed",Toast.LENGTH_LONG).show()
    }

    override fun onUpgrade(db: SQLiteDatabase?, oldVersion: Int, newVersion: Int) {
//        TODO("not implemented") //To change body of created functions use File | Settings | File Templates.
        db?.execSQL("drop table if exists Book")
        onCreate(db)
    }
}

对数据进行操作
操作比较简单,下面直接看代码:
Activity中

class MySQLite : AppCompatActivity() {

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_my_sqlite)
        val dbHelper=MyDatabaseHelper(this,"BookStore.db",1)
        /**
         * 创建表
         */
        btnCreateDataBase.setOnClickListener {
            dbHelper.writableDatabase
        }
        /**
         * 添加数据
         */
        btnAddData.setOnClickListener {
            val db=dbHelper.writableDatabase
            val Values1=ContentValues().apply {
//                第一条数据
                put("name","The Da Vinci Code")
                put("author","Dan Broen")
                put("pages",454)
                put("price",16.96)
            }
            db.insert("Book",null,Values1)
            val  values2=ContentValues().apply {
//                第二条数据
                put("name","The Lost Symbol")
                put("author","Dan Brown")
                put("pages",510)
                put("price",19.95)
            }
            db.insert("Book",null,values2)
        }
        btnUpdateData.setOnClickListener {
            val db=dbHelper.writableDatabase
            val values=ContentValues()
            values.put("price",10.99)
            db.update("Book",values,"name=?", arrayOf("The Da Vinci Code"))
        }
        btnDeleteData.setOnClickListener {
            val db=dbHelper.writableDatabase
            db.delete("Book","pages>?", arrayOf("500"))
        }
        btnQueryData.setOnClickListener {
            val db=dbHelper.writableDatabase
//            查询Book表中所有数据
//            这里获取到是Cursor对象
            val cursor=db.query("Book",null,null,null,null,null,null)
            if (cursor.moveToFirst()){
                do {
                    val name=cursor.getString(cursor.getColumnIndex("name"))
                    val author=cursor.getString(cursor.getColumnIndex("author"))
                    val pages=cursor.getString(cursor.getColumnIndex("pages"))
                    val price=cursor.getString(cursor.getColumnIndex("price"))
                    Log.d("MainActivity","book name is $name")
                    Log.d("MainActivity","author is $author")
                    Log.d("MainActivity","pages is $pages")
                    Log.d("MainActivity","price is $price")
                }while (cursor.moveToNext())
            }
            cursor.close()
        }
    }
}

布局文件

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".sqlite.MySQLite">

    <Button
        android:id="@+id/btnCreateDataBase"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="CreateDataBase"
        android:textAllCaps="false"
        app:layout_constraintTop_toTopOf="parent" />

    <Button
        android:id="@+id/btnAddData"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="AddData"
        android:textAllCaps="false"
        app:layout_constraintTop_toBottomOf="@+id/btnCreateDataBase" />

    <Button
        android:id="@+id/btnUpdateData"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="UpdateData"
        android:textAllCaps="false"
        app:layout_constraintTop_toBottomOf="@+id/btnAddData" />

    <Button
        android:id="@+id/btnDeleteData"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="DeleteData"
        app:layout_constraintTop_toBottomOf="@+id/btnUpdateData" />

    <Button
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:id="@+id/btnQueryData"
        android:text="Query Data"
        android:textAllCaps="false"
        app:layout_constraintTop_toBottomOf="@+id/btnDeleteData"/>
</androidx.constraintlayout.widget.ConstraintLayout>

到此这篇关于Android Kotlin使用SQLite案例详解的文章就介绍到这了,更多相关Android Kotlin使用SQLite内容请搜索华域联盟以前的文章或继续浏览下面的相关文章希望大家以后多多支持华域联盟!

本文由 华域联盟 原创撰写:华域联盟 » Android Kotlin使用SQLite案例详解

转载请保留出处和原文链接:https://www.cnhackhy.com/109676.htm

本文来自网络,不代表华域联盟立场,转载请注明出处。

作者: sterben

发表回复

联系我们

联系我们

2551209778

在线咨询: QQ交谈

邮箱: [email protected]

工作时间:周一至周五,9:00-17:30,节假日休息

关注微信
微信扫一扫关注我们

微信扫一扫关注我们