SwiftUI study notes [Sqlite]

Preface

Mobile terminal development can store data in localization 文件储存[that is, NSUserDefaultsthe essence of writing to a local file is to store data in a file in the form of key=value plist]. Of course, a large amount of data dictionary storage still has to be powerful sqlite.

One, SQLiteDB-integration

1. Download the frame file

  • SQLiteDB official website to download the file unzip to get critical .swift framework document [ CloudDB.swift, SQLTable.swift, SQLiteBase.swift, SQLiteDB.swift].

2. Then drag to the item

It should be noted here that the swift file should be globally accessible, and there is no need to introduce the header file, but it may be invalid, so I just throw it directly under the project without grouping.

3. Xcode add db file

In Build Phasesthe following add .dbfiles, where .dbfiles can be your own or the company's new database .db file [Note that the need to modify SQLiteBase.swift which DB_NAMEis imported .db file name], of course, too lazy to download the official package inside It is also possible to add data.db. How to operate your own library will also be written later.

4. Create new overseas Chinese receiving documents

Right click on the project name to create a new file -> select the Cocoa Touch Classfile and click Next

Enter the name of the overseas Chinese class and just name it here [ brid_head], select Subclass of, select UIViewLanguage, and Objective-Cclick Next.

Select swiftUIStudy as follows and click Create

Some Xcode may automatically prompt to generate overseas Chinese receiving files. You can click ok to automatically generate and 项目名_Bridging-Header.hfinally delete the brid_head.h and brid_head.m files, but sometimes, like my Xcode, it can automatically generate the overseas connection file, and sometimes it will not generate the bridge file. At this time, we only need to copy the following statement to the brid_head.hfile or 项目名_Bridging-Header.hinside.

#import "sqlite3.h"
#import <time.h>

Then we go to click on the item as shown in the figure 1—> Build Setting-----> 图中2 combined-----> Swift Compiler - GeneralDouble-click the blank space behind Objective-C Bridging Header to drag or paste the path of brid_head.h.

Second, SQLiteDB-operation

1. Create a new UI page

New dedicated page for operating database

2.SQLiteDB source code reading

///1.shared源码这里初始化创建SQLiteDB实例static修饰作为单利提供给外界访问。
/// Singleton instance for access to the SQLiteDB class
    static let shared = SQLiteDB()

//2.dbPath作为本地数据库路径。根据代码我们可以看出如果dbPath为null那么默认会获取项目下的DB_NAME=data.db
//作为空数据库容器,inMemory是使用内存数据库还是磁盘数据库。我们以db文件的形式就是默认false即磁盘数据库
override func open(dbPath: String = "", copyFile: Bool = true, inMemory: Bool = false) -> Bool {
    NSLog("DB Open called with path: \(dbPath)")
    var path = ""
    if !inMemory {
        if dbPath.isEmpty {
            guard let url = Bundle.main.resourceURL else { return false }
            path = url.appendingPathComponent(DB_NAME).path
        } else {
            path = URL(fileURLWithPath: dbPath).path
        }
    }
    NSLog("Calling Super Open with path: \(path)")
    return super.open(dbPath: path, copyFile: copyFile, inMemory: inMemory)
} 

.
.
.
.
封装了很多方法可以自己看哦

3. Initial use of SQLiteDB

By SQLiteDB.sharedinstantiating SQLiteDB, .open()opening the database, and then .execute(sql:"数据库操作语句")performing operations. The following code:

import SwiftUI

struct Swift_Sqlite_UIView: View {
    //1.获取数据库实例
    var db:SQLiteDB=SQLiteDB.shared
    var body: some View {
        VStack(){
            Text("SQLiteDB操作").modifier(TitleStyle())
            //1.数据库操作打开DB链接
            HStack{
                Text("open").onTapGesture {
                //2.这里进行打开数据库
                _=self.db.open()
                //3.执行创建表操作操作
                _=self.db.execute(sql: "create table if not exists users(uid integer primary key,uname varchar(20),description varchar(20))")
                print("path=\(homePath())")
                }.modifier(Title())    
           }.modifier(StackStyle(alignment:Alignment.topLeading))  
        }.modifier(StackStyle(alignment:Alignment.top))
        
    }
}

struct Swift_Sqlite_UIView_Previews: PreviewProvider {
    static var previews: some View {
        Swift_Sqlite_UIView()
    }
}




//modifier
struct TitleStyle: ViewModifier {
    func body(content: Content) -> some View {
        content.padding(EdgeInsets(top: 66,leading: 1,bottom: 1,trailing: 1)).font(/*@START_MENU_TOKEN@*/.title/*@END_MENU_TOKEN@*/)
    }
}

struct Title: ViewModifier {
    func body(content: Content) -> some View {
        content.padding(EdgeInsets(top: 16,leading: 11,bottom: 1,trailing: 1)).font(.title)
    }
}
struct StackStyle: ViewModifier{
    var alignment=Alignment.top
    var screenBounds:CGRect = UIScreen.main.bounds
    func body(content: Content) -> some View {
        content.frame(width:screenBounds.width, height: screenBounds.height, alignment:alignment)
    }
}
  • Before running, remember to change the running start interface as follows before running:

Then click open, and we see that the return result is 1. The creation is successful.

4. Whether the table was built successfully[验证]

In the code, we have printed the path of the simulator, we need to click in to see if the table is created successfully. We speak of the facts. With the following code, we can print the simulator path:

func homePath() -> NSString {
        
        return NSHomeDirectory() as NSString;
        
}

Open the terminal and enter the open path as follows:

  • Click Enter, a bunch of folders appear with a highlighted folder in Figure 1, click Documents->data.db appears

  • Click Documents or Library->data.db appears, we use Navicat Premium and other tools to open the database to view the table

  • View the data.db table as follows 验证成功:

5.SQLiteDB-增查改删存粹的sql语句拼接

The reason why SQLiteDB is easy to use is to use SQL statements straightforwardly.

【1】:
 Text("insert").onTapGesture {
    let uname = "王飞"
    let description = "路很长"
    //插入数据库,这里用到了esc字符编码函数,其实是调用bridge.m实现的
    let sql = "insert into persons(uname,description) values('\(uname)','\(description)')"
    print("sql: \(sql)")
    //通过封装的方法执行sql
    let result = db.execute(sql: sql)
    print(result)
}.modifier(Title())
  • Run to see the effect in the same way, get the path terminal to open, and view the data table插入成功!

【2】:
   //查询数据
    Text("select").onTapGesture {
        let uname = "王飞"
        //插入数据库,这里用到了esc字符编码函数,其实是调用bridge.m实现的
        let sql = "select uname from persons where uname='\(uname)'"
        print("sql: \(sql)")
        //通过封装的方法执行sql
        let result = db.query(sql: sql)
        //获取最后一行数据显示
        let name = result[0]["uname"] as? String
        print("数据库数据来了=\(String(describing: name))")
    }.modifier(Title())

打印结果ok

【3】:
      //跟新数据
      Text("updata").onTapGesture {
          let uname = "大飞飞"
          //插入数据库,这里用到了esc字符编码函数,其实是调用bridge.m实现的
          let sql = "update persons set uname = '\(uname)'"
          print("sql: \(sql)")
          //通过封装的方法执行sql
          _ = db.execute(sql: sql)


          //查询
          let selectSql = "select uname from persons"
          print("sql: \(selectSql)")
          //通过封装的方法执行sql
          let results = db.query(sql: selectSql)

          let name = results[0]["uname"] as? String
          print("修改之后的数据=\(String(describing: name))")
      }.modifier(Title())
【4】:

Remember that each run needs to be reopened, inserted, and then deleted. Otherwise, report an error 超出索引异常.

 //删除数据
  HStack{
      Text("delete").onTapGesture {
          let uname = "大飞飞"
          //删除满足条件数据

          let sql = "delete from persons where uname = '\(uname)'"
          print("sql: \(sql)")
          //通过封装的方法执行sql
          _ = db.execute(sql: sql)

          //查询
          let selectSql = "select *from persons"
          print("sql: \(selectSql)")
          //通过封装的方法执行sql
          let results = db.query(sql: selectSql)

          let name = results.count
          print("修改之后的数据个数=\(String(name))个")
      }.modifier(Title())
  }.modifier(StackStyle(alignment:Alignment.topLeading,height: 66))

            

Three, SQLiteDB- 操作任意.db文件, modify DB_NAME="bhnes.db" in SQLiteDB.swift

The operation is as follows, add bhnes.db,

  • The table structure is as follows:

  • code show as below

 VStack{
                Text("操作其他.db文件").onTapGesture {
                    db.open()
                    let uname = "大飞飞"
                    //删除满足条件数据
                    
                    let sql = "delete from persons where uname = '\(uname)'"
                    print("sql: \(sql)")
                    //通过封装的方法执行sql
                    _ = db.execute(sql: sql)
                
                    //查询
                    let selectSql = "select *from persons"
                    print("sql: \(selectSql)")
                    //通过封装的方法执行sql
                    let results = db.query(sql: selectSql)
                    
                    let name = results.count
                    print("修改之后的数据个数=\(String(name))个")
                }.offset(x:80.0, y:10).modifier(TitleStyle()).foregroundColor(.red)
                
                Text("查询").onTapGesture {
                    _=self.db.open()
                    //插入数据库,这里用到了esc字符编码函数,其实是调用bridge.m实现的
                    let sql = "select name from EquipType where code='Z'"
                    print("sql: \(sql)")
                    //通过封装的方法执行sql
                    let result = db.query(sql: sql)
                    //获取最后一行数据显示
                    let name = result[0]["name"] as? String
                    print("数据库数据来了=\(String(describing: name))")
                    
                    DispatchQueue.main.async {
                        if (!(name!.isEmpty)){
                           self.queryResult = name! as String
                           self.flag=true
                        }
                    }
                    
                    
                    
                    
                }.modifier(Title()).offset(x: -60.0, y: 10.0)
            
                Text(self.flag ?   queryResult : "查询结果").modifier(Title())
                             
            }.modifier(StackStyle(alignment:Alignment.topLeading,height: 266))

  • Click the query button: follow the new control as follows

Next we proceed to operate our own database.
....下午继续

Guess you like

Origin blog.csdn.net/m0_37667770/article/details/110849971