How to write SQL in js
In the ever-changing front-end field, front-end engineers can do more and more things. Since the emergence of nodejs, the front-end has increasingly had a tendency to revolutionize the traditional back-end life. This article will add one more detail. Interpret how to execute standard SQL statements in js code
Why write SQL in js?
As business complexity increases, some pages with complex data logic may appear on the front-end page. Traditional js logic is more complicated to process. Let’s look at two examples first:
For example, in the multi-specification and multi-inventory product interface, the difficulty lies in the complex logical relationship between color classification, size, price, inventory, limited purchase quantity and corresponding picture display. Users perform different When selecting, js needs to go through many complex queries to calculate the result
For example, the difficulty in the regional linkage query interface is:
How to store regional data locally? Obviously it is unrealistic to pull the interface every time. If it is stored in storage, every time it is used, a string similar to JSON.parse needs to be converted into an array or object. process, this operation will cause page freezes and extremely poor performance when the amount of data is large.
The three-level regional linkage query is complicated. If you want to query from a county-level region to the corresponding For cities and provinces, the logic will be more complicated
If the above two examples are written using traditional js logic, everyone must have already designed them in their minds Algorithms inevitably use various ES678 new methods such as forEach, filter, some, find, etc. The author also used various cool new methods to write it and found two problems:
-
After writing it, the logic is very complicated. It seems that it cannot be implemented without 100 lines of code (of course there are masters who can do it better than me)
Even if I write a lot of comments, my colleagues can’t see it I'm still confused (because the logic is really complicated...)
The author has been doing PHP development for a while (also done PM, UI, QA, etc.) and suddenly thought Can it be implemented using SQL? After some research, the author wrote such a library:
Database.js
Database.js is based on Web SQL Database, so what is Web SQL Database?
Web SQL Database is the first official draft proposed by WHATWG (Web Hypertext Application Technology Working Group, the proposer of the HTML5 draft) in January 2008, but it is not included in HTML 5 specification, it is an independent specification that introduces a set of APIs for operating client databases using SQL. Since it was proposed earlier, although the W3C officially stated in November 2011 that it would no longer maintain the Web SQL Database specification, these APIs have been widely implemented in different browsers, especially mobile browsers.
Compatibility
What is the difference between Web SQL Database and Indexed Database?
Indexed Database is more similar to NoSQL in operating the database. The most important thing is that Indexed Database does not use SQL as the query language.
In order to realize the need to write SQL in js, the author decisively adopted the former as the underlying technology.
Web SQL Database three core methods:
-
openDatabase: This method uses an existing database or a new database to create a database object
transaction: This method allows us to control transaction submission or rollback depending on the situation
executeSql: This method is used to execute SQL queries
Code example:
var db = openDatabase('testDB', '1.0', 'Test DB', 2 * 1024 * 1024); var msg; db.transaction(function (context) { context.executeSql('CREATE TABLE IF NOT EXISTS testTable (id unique, name)'); context.executeSql('INSERT INTO testTable (id, name) VALUES (0, "Byron")'); context.executeSql('INSERT INTO testTable (id, name) VALUES (1, "Casper")'); context.executeSql('INSERT INTO testTable (id, name) VALUES (2, "Frank")'); });
For front-end students who have no SQL experience, the above code looks a bit unfamiliar and not very friendly. , so Database.js was born:
The author takes a demand in the business as an example: Zhuanzhuan Game Business List Page The filter menu is a three-level linkage menu. Each menu change will affect other menu data, as shown in the figure:
Original JSON data structure
It can be seen that it is a three-level nested structure. The author processed it into a flat data structure (the process is omitted) and stored it in three databases, respectively storing game names, game platforms, and product types, as follows Picture:
An example of the game name data structure is as follows:
通过chrome控制台Application面板可以直接看到数据库,结构、数据清晰可见
核心代码如下:
/** * 打开数据库 * @returns {Promise.<void>} */ openDataBase(){ //打开数据库,没有则创建 db.openDatabase('GameMenu',1,'zzOpenGameMenu').then(res=>{ //检测数据库是否存在 db.isExists('game').then(res=>{ //数据库已经存在,直接使用,将数据交付给页面UI组件 this.setSelectData() }).catch(e=>{ //数据库不存在,请求接口并处理数据,然后存入数据库 this.getData() }) }).catch(e=>{ console.err(e) }) }, /** * 获取分类数据并存储到数据库 * @returns {Promise.<void>} */ async getData(){ //接口请求数据并处理成三个扁平数组 let data = await this.getMenuData() for(let i in data){ //创建表并存储数据 db.create(i,data[i]) } //将数据交付给页面UI组件 this.setSelectData() },
当任意菜单选择变更时,三列数据将重新查询,核心代码如下:
/** * 重新查询数据 * @param data 点击菜单携带的数据 * @param index 点击菜单的序号 * @param all 三个菜单当前选中数据 */ async onSelect(data,index,all){ let target = [],condition = {} //业务逻辑:处理查询条件 if(all['0'] && all['0']['name']!=defaultData[0].default.name)condition['gameName'] = all['0']['name'] if(all['1'] && all['1']['name']!=defaultData[1].default.name)condition['platName'] = all['1']['name'] if(all['2'] && all['2']['name']!=defaultData[2].default.name)condition['typeName'] = all['2']['name'] //创建三个查询任务 let tasks = ['game','plat','type'].map((v,k)=>{ //使用db.select方法查询 return db.select(v,this.formatCondition(v,condition),'name,value','rowid desc','name').then((res)=>{ target.push({ options:res.data, defaultOption:defaultData[k].default, clickHandle:this.onSelect }) }) }) //执行查询 await Promise.all(tasks) //将数据交付给联动菜单组件使用 this.selectData = target }
以上代码即可完成联动菜单所需要的数据管理工作,看起来是不是比较清晰?
使用Database.js的优势
1.将数据结构化存储于Storage中,避免了以文本形式存入Storage或cookie中再解析的性能消耗流程。
2.将复杂数据清晰的在前端进行管理和使用,代码逻辑更清晰,数据查询更简洁!
Database.js使用文档
openDatabase
功能:打开数据库,不存在则创建
语法:openDatabase(dbName,dbVersion,dbDescription,dbSize,callback)
参数:
dbName:数据库名
dbVersion:数据库版本(打开已存在数据库时,版本号必须一致,否则会报错)
dbDescription:数据库描述
dbSize:数据库预设大小,默认1M
callback:回调函数
query
功能:执行sql语句,支持多表查询
语法:query(sqlStr,args = [],callback,errorCallback)
参数:
sqlStr:sql语句
args(Array):传入的数据,替换sql中的?符号
callback:成功回调
errorCallback:失败回调
1 //插入数据 2 db.query('INSERT INTO testTable(id,title) VALUES (?,?)',[1,'这是title']) 3 4 //多表查询 5 db.query('select game.*,plat.* from game left join plat on game.name = plat.gameName')
isExists
功能:检测表是否存在
语法:isExists(tableName)
参数:
tableName:表名
createTable
功能:创建一张表
语法:createTable(tableName,fields)
参数:
tableName:表名
fields:表结构(需指定字段类型)
示例
1 db.createTable('testTable',{ 2 name:'varchar(200)', 3 price:'int(100)' 4 })
insert
功能:插入一条或多条数据
语法:insert(tableName,data)
参数:
tableName:表名
data(Object or Array):插入的数据,多条数据请传入数组类型
示例:
javascript //插入单条 db.insert('testTable',{ name:'商品1', price:10 }) //插入多条 db.insert('testTable',[ {name:'商品1',price:10}, {name:'商品2',price:20}, {name:'商品3',price:30}, ])
将数据存入数据库的常规流程是先createTable,然后再insert,如果你觉得这样麻烦,可以试一下create方法:
create
功能:直接创建数据库并存入数据
注意:类库会根据传入的数据类型自动设置数据库的字段类型,这样可以覆盖大多数需求,但如果你的数据中,同一个字段中有不同的数据类型,有可能不能兼容,建议还是使用常规流程手动设置类型
语法:create(tableName,data)
参数:
tableName:表名
data(Object or Array):插入的数据,多条数据请传入数组类型
示例:
1 //插入数据 2 db.query('INSERT INTO testTable(id,title) VALUES (?,?)',[1,'这是title']) 3 4 //多表查询 5 db.query('select game.*,plat.* from game left join plat on game.name = plat.gameName')
delete
功能:删除数据
语法:delete(tableName,condition)
参数:
tableName:表名
condition(String or Obejct):查询条件
示例:
1 //删除一条数据 2 db.delete('testTable',{name:'商品1'})
关于condition: 1、传入array形式时,默认查询条件连接方式是AND,如果需要用OR等方式,可以在condition中传入logic设定,例如{logic:'OR'} 2、如果查询条件有AND、OR等多种方式,建议使用string方式传入
select
功能:查询数据
注意:如果需要多表查询,可参照query方法
语法:select(tableName,condition = '',fields = '*',order = '',group = '',limit = '')
参数:
tableName:表名
condition(String or Obejct):查询条件
fields(String or Array):返回字段,默认*,支持distinct
order(String or Array):排序规则
group(String or Array):分组规则
limit(String or Array):分页规则
示例:
1 //查询name=商品1的数据,并按照price倒序
Copy after login
**update** - 功能:更新数据 - 语法:update(tableName,data,condition = '') - 参数: - tableName:表名 - data(String or Obejct):更改数据 - condition(String or Obejct):查询条件 - 示例:
1 //将商品1的价格改为99 2 db.update('testTable',{ 3 price:99 4 },{ 5 name:'商品1' 6 })
truncate
功能:清空表
语法:truncate(tableName)
参数:
tableName:表名
drop
功能:删除表
语法:drop(tableName)
参数:
tableName:表名
The above is the detailed content of How to write SQL in js. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics











WeChat is one of the mainstream chat tools. We can meet new friends, contact old friends and maintain the friendship between friends through WeChat. Just as there is no such thing as a banquet that never ends, disagreements will inevitably occur when people get along with each other. When a person extremely affects your mood, or you find that your views are inconsistent when you get along, and you can no longer communicate, then we may need to delete WeChat friends. How to delete WeChat friends? The first step to delete WeChat friends: tap [Address Book] on the main WeChat interface; the second step: click on the friend you want to delete and enter [Details]; the third step: click [...] in the upper right corner; Step 4: Click [Delete] below; Step 5: After understanding the page prompts, click [Delete Contact]; Warm

Unfortunately, people often delete certain contacts accidentally for some reasons. WeChat is a widely used social software. To help users solve this problem, this article will introduce how to retrieve deleted contacts in a simple way. 1. Understand the WeChat contact deletion mechanism. This provides us with the possibility to retrieve deleted contacts. The contact deletion mechanism in WeChat removes them from the address book, but does not delete them completely. 2. Use WeChat’s built-in “Contact Book Recovery” function. WeChat provides “Contact Book Recovery” to save time and energy. Users can quickly retrieve previously deleted contacts through this function. 3. Enter the WeChat settings page and click the lower right corner, open the WeChat application "Me" and click the settings icon in the upper right corner to enter the settings page.

Colorful motherboards enjoy high popularity and market share in the Chinese domestic market, but some users of Colorful motherboards still don’t know how to enter the bios for settings? In response to this situation, the editor has specially brought you two methods to enter the colorful motherboard bios. Come and try it! Method 1: Use the U disk startup shortcut key to directly enter the U disk installation system. The shortcut key for the Colorful motherboard to start the U disk with one click is ESC or F11. First, use Black Shark Installation Master to create a Black Shark U disk boot disk, and then turn on the computer. When you see the startup screen, continuously press the ESC or F11 key on the keyboard to enter a window for sequential selection of startup items. Move the cursor to the place where "USB" is displayed, and then

Tomato Novel is a very popular novel reading software. We often have new novels and comics to read in Tomato Novel. Every novel and comic is very interesting. Many friends also want to write novels. Earn pocket money and edit the content of the novel you want to write into text. So how do we write the novel in it? My friends don’t know, so let’s go to this site together. Let’s take some time to look at an introduction to how to write a novel. Share the Tomato novel tutorial on how to write a novel. 1. First open the Tomato free novel app on your mobile phone and click on Personal Center - Writer Center. 2. Jump to the Tomato Writer Assistant page - click on Create a new book at the end of the novel.

Mobile games have become an integral part of people's lives with the development of technology. It has attracted the attention of many players with its cute dragon egg image and interesting hatching process, and one of the games that has attracted much attention is the mobile version of Dragon Egg. To help players better cultivate and grow their own dragons in the game, this article will introduce to you how to hatch dragon eggs in the mobile version. 1. Choose the appropriate type of dragon egg. Players need to carefully choose the type of dragon egg that they like and suit themselves, based on the different types of dragon egg attributes and abilities provided in the game. 2. Upgrade the level of the incubation machine. Players need to improve the level of the incubation machine by completing tasks and collecting props. The level of the incubation machine determines the hatching speed and hatching success rate. 3. Collect the resources required for hatching. Players need to be in the game

A summary of how to obtain Win11 administrator rights. In the Windows 11 operating system, administrator rights are one of the very important permissions that allow users to perform various operations on the system. Sometimes, we may need to obtain administrator rights to complete some operations, such as installing software, modifying system settings, etc. The following summarizes some methods for obtaining Win11 administrator rights, I hope it can help you. 1. Use shortcut keys. In Windows 11 system, you can quickly open the command prompt through shortcut keys.

Detailed explanation of Oracle version query method Oracle is one of the most popular relational database management systems in the world. It provides rich functions and powerful performance and is widely used in enterprises. In the process of database management and development, it is very important to understand the version of the Oracle database. This article will introduce in detail how to query the version information of the Oracle database and give specific code examples. Query the database version of the SQL statement in the Oracle database by executing a simple SQL statement

Setting font size has become an important personalization requirement as mobile phones become an important tool in people's daily lives. In order to meet the needs of different users, this article will introduce how to improve the mobile phone use experience and adjust the font size of the mobile phone through simple operations. Why do you need to adjust the font size of your mobile phone - Adjusting the font size can make the text clearer and easier to read - Suitable for the reading needs of users of different ages - Convenient for users with poor vision to use the font size setting function of the mobile phone system - How to enter the system settings interface - In Find and enter the "Display" option in the settings interface - find the "Font Size" option and adjust it. Adjust the font size with a third-party application - download and install an application that supports font size adjustment - open the application and enter the relevant settings interface - according to the individual
