目录
一 SQLite数据库介绍
SQLite 是关系型数据库:使用通用的 SQL 语句进行管理 (同oracle mySql)
SQLite 是嵌入式的数据库:使用在小设备上的数据库(比如 手表、手机) → 体积小,功能强大
SQLite数据库是由底层的sqlite.c来动态创建我们的数据库 (MySql、SqlServer都是用户手动创建数据库)
支持多种数据格式,比如int varchar char,但都会转成TEXT(字符串文本)这种格式
主键一般两点要求:
1 命名必须是:_id (下划线id)
2 格式必须是Integer
二 SQLite使用步骤
1 创建工具类mySQLiteOpenHelper 继承 SQLiteOpenHelper,使用单例模式获取到实例
2 创建数据库getWritableDatabase()
3 创建表db.execSQL(sql)
三 代码和运行结果
布局
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout 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=".MainActivity3">
<Button
android:text="生成DB文件"
android:onClick="createDB"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
</LinearLayout>
工具类
package com.example.mydatastroe;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;
import androidx.annotation.Nullable;
/**
* 工具类 单例模式(1 构造函数私有化,2 对外提供函数)
*/
public class MySQLiteOpenHelper extends SQLiteOpenHelper {
//2 对外提供函数
private static MySQLiteOpenHelper myInstansce;
public synchronized static MySQLiteOpenHelper getInstance(Context context){
if(myInstansce == null){
myInstansce = new MySQLiteOpenHelper(context,"qingDB.db",null,1); //以后想要做数据库升级,把1改成2
}
return myInstansce;
}
//1 构造函数私有化 (有数据库的名字 数据库的版本号 → 拿到这些信息才能有能力创建数据库)
private MySQLiteOpenHelper(@Nullable Context context, @Nullable String name, @Nullable SQLiteDatabase.CursorFactory factory, int version) {
super(context, name, factory, version);
}
//创建表,表数据初始化,数据库第一次创建的时候调用,第2次发现有了,就不会重复创建了,也意味着此函数只会创建一次
//数据库初始化用的
@Override
public void onCreate(SQLiteDatabase db) {
//创建表
//主键一般两点要求:
// 1 命名必须是:_id (下划线id)
// 2 格式必须是Integer
// 主键自动增长: autoincrement
// 创建了两列:_id,name
String sql = "create table people(_id integer primary key autoincrement,name text)";
db.execSQL(sql);
}
//数据库升级用的
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
}
}
MainActivity.java
package com.example.mydatastroe;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
public class MainActivity3 extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main3);
}
//创建db
public void createDB(View view) {
MySQLiteOpenHelper helper = MySQLiteOpenHelper.getInstance(this);
//databases 文件夹的创建靠:getWritableDatabase/getReadableDatabase
helper.getWritableDatabase();
}
}
代码运行之前看一下这里是没有数据库的
运行程序,点button
刷新看到了这里创造出数据库了
把文件存到本地(注意:3个文件都要存过来,否则只能看到数据库,看不到表)
接下来我们用可视化工具SQLiteExpertPro看一下生成的数据库
表里的这两列创建出来了