Android中SQLite数据库简单创建

可以定义一个DBHelper类继承自SQLiteOpenHelper,调用父类的构造方法super(context,DB_NAME,null,DB_VERSION)
自动创建名为 DB_NAME 的数据库。其中建表的操作可以在 MainActivity.java 的 onCreate() 方法中执行。具体代码见下:

MainActivity.java

package com.example.anli5_301;

import androidx.appcompat.app.AppCompatActivity;

import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;

public class MainActivity extends AppCompatActivity {
    private DBHelper dbHelper = null;
    private SQLiteDatabase mDB = null;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        init();
    }
    private void init() {
        //实例化SQLiteOpenHelper的子类对象DBHelper
        dbHelper=new DBHelper(this);
        //获取到SQLiteDatabase对象
        mDB = dbHelper.getWritableDatabase();
    }
}

DBHelper.java

package com.example.anli5_301;

import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;

public class DBHelper extends SQLiteOpenHelper {
    private static final int DB_VERSION = 1;//数据库版本号
    private static final String DB_NAME = "student.db";//数据库名称
    private static final String TABLE_NAME = "score";//创建的表名称
    public DBHelper(Context context) { //接收Context参数的构造方法
        super(context, DB_NAME, null, DB_VERSION);//调用父类构造方法创建数据库
    }

    public void onCreate(SQLiteDatabase db) {
        String sql = "create table if not exists " + TABLE_NAME + "(stuNo text primary key, stuName text,stuSex text, stuScore integer)";//创建表的语句
        db.execSQL(sql);//执行创建表的sql语句
    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {

    }
}

布局文件(自动生成的,我没动)

<?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=".MainActivity">

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Hello World!"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

</androidx.constraintlayout.widget.ConstraintLayout>

运行生成的数据库文件在 DFE中,如下:
在这里插入图片描述

发布了17 篇原创文章 · 获赞 26 · 访问量 5611

猜你喜欢

转载自blog.csdn.net/weixin_43624626/article/details/105646614