2021-03-24 indexDb数据库存储数据操作

直接上代码,示例代码如下:

class App extends React.PureComponent {
    private objectStore;
    private request = window.indexedDB.open('dataBaseName', 1)
    private db
    constructor(props){
        this.init()
   }
    init=()=>{
        let that = this
        this.request.onerror = function (event) {
            alert("Why didn't you allow my web app to use IndexedDB?!");
        };
        this.request.onsuccess = function (event) {
            console.log('连接数据库成功', event)
            const { result }: any = event.target;
            that.db = result
            console.log('连接数据库成功db', that.db)
            // 为该数据库创建一个对象仓库  这个相当于表
        };
        this.request.onupgradeneeded = function (event) {
            // 创建一个数据库存储对象,并指定主键
            that.objectStore = that.db.createObjectStore('person', {
                keyPath: 'id',
                autoIncrement: true
            });

            // 定义存储对象的数据项 
            // 第一个参数是创建的索引名称,可以为空
            // 第二个参数是索引使用的关键名称,可以为空
            // 第三个参数是可选配置参数,可以不传,常用参数之一就是 unique ,表示该字段是否唯一,不能重复
            that.objectStore.createIndex('id', 'id', {
                unique: true
            });
            that.objectStore.createIndex('name', 'name');
            that.objectStore.createIndex('age', 'age');
            that.objectStore.createIndex('sex', 'sex');
        }
    }
      //开启事务添加数据到数据库
     addData = () => {
        var transaction = this.db.transaction(["person"], "readwrite");
        let newItem = {
            id: 1,
            name: '徐嘻嘻1',
            age: 1,
            sex: 'man'
        };
        var objectStore = transaction.objectStore("person");
        // 添加到数据对象中, 传入javascript对象
        objectStore.add(newItem);
        transaction.oncomplete = function (event) {
            console.log("All done!",event);
           
        };
        transaction.onerror = function (event) {
            // Don't forget to handle errors!
            console.log('插入数据失败!', event)
        };
     }
}

你可能感兴趣的:(2021-03-24 indexDb数据库存储数据操作)