[Express.js] sql-knex addition, deletion, modification and query

Sql add, delete, modify and check

This section uses knex as the sql framework, taking the sqlite database as an example

Preparation

knex is a framework that runs on the respective database Driver, so you need to install the corresponding js version of the database driver, such as: PostgreSQL -> pg, mysql/mariadb -> mysql, sqlite -> sqlite3…

  • Install sqlite3 dependenciesnpm install sqlite3
  • Install knex dependenciesnpm install knex
  • Introduce dependencies
const app = express();
const knex = require('knex');
  • It is recommended to install a suitable database interface tool, the author uses Beekeeper Studio.

create project

Copy the first section of the HelloWorld project

create sqlite connection

Specify the client as sqlite3 (the sqlite3 just installed depends on it), and specify the sqlite database path to be operated

const sqlite = knex({
    client: 'sqlite3',
    connection: {
      filename: './data.db',
    },
});

Once a connection instance is created, a connection pool is automatically created, so initializing the database only happens once

connection configuration

The default of sqlite3 is single connection, if you want more connections in the connection pool, bring the pool when creating:

const sqlite = knex({
    
    
    client: 'sqlite3',
    connection: {
    
    
      filename: './data.db',
    },
    pool: {
    
     min: 0, max: 7 }
});

Create a connection pool callback

Used to check whether the connection pool is normal, usually this step is not needed

pool: {
    afterCreate: function (conn, done) {//...}
}

acquireConnectionTimeout

connection timeout

log

knex has built-in log functions that print warnings, errors, deprecations, and debugging information. If you want to customize log operations, you can override them in the log item

log: {
    warn(message) {
    },
    error(message) {
    },
    deprecate(message) {
    },
    debug(message) {
    }
}

data sheet

build table

grammar:sqlite.schema.createTable(表名, table=>{表结构})

Add a PUT interface, listen to 127.0.0.1:8080/db/:tbname
and try to create a table according to the table name we want to create. Note: SQL execution is asynchronous. In order to get the result, it is recommended to use async/await syntactic sugar (of course you It’s not bad even if you like hell callbacks)

app.put('/db/:tbname', async function (req, res) {
    
    
    let resultSet = null;
    try {
    
    
        // Create a table
        resultSet = await sqlite.schema
          .createTable(req.params.tbname, table => {
    
    
            table.increments('id');
            table.string('uname');
            table.string('passwd');
          })
        // Finally, add a catch statement
      } catch(e) {
    
    
        console.error(e);
        resultSet = e;
    };
    res.json(resultSet);
});

Take a look at the console:

sqlite does not support inserting default values. Set the `useNullAsDefault` flag to hide this warning. (see docs https://knexjs.org/guide/query-builder.html#insert).

Um? sqlite does not support default? Don’t worry about him, go to the database, anyway, the user table is successfully created, if you add useNullAsDefaultthis flag, it will tell you not supported by node-sqlite3

const sqlite = knex({
    
    
    client: 'sqlite3',
    connection: {
    
    
      filename: './data.db',
    },
});

delete table

grammar:sqlite.schema.deleteTable(表名)

app.delete('/db/:tbname', async function (req, res) {
    
    
    try {
    
    
        // Delete a table
        await sqlite.schema.dropTable(req.params.tbname);
        // Finally, add a catch statement
      } catch(e) {
    
    
        console.error(e);
    };
    res.json(null);
});

table record crud

increase

Insert a new record into the user table

app.use(express.json({
    
    type: 'application/json'}));
app.put('/db/:tbname/record', async function (req, res) {
    
    
    /*前端请求体格式:
    {
        "uname": "evanp",
        "passwd": "iloveu"
    }
    */
   let resultSet = null;
    try {
    
    
        // Insert a record
        resultSet = await sqlite(req.params.tbname).insert(req.body);
        // Finally, add a catch statement
      } catch(e) {
    
    
        console.error(e);
        resultSet = e;
    };
    res.json(resultSet);
});

Try to use the api debugging tool PUT 127.0.0.1:8080/db/user/record, carry the corresponding request body, you will get [1], this is the number of records affected, 1 means success

check

Query uname=the record we just inserted from the user table

app.get('/db/:tbname/record', async function (req, res) {
    
    
    //前端携带query: uname=evanp
   let resultSet = null;
    try {
    
    
        // select a record where uname=xxx
        resultSet = await sqlite(req.params.tbname).select('*').where('uname',req.query.uname);
        // Finally, add a catch statement
      } catch(e) {
    
    
        console.error(e);
        resultSet = e;
    };
    res.json(resultSet);
});

Try to use the api debugging tool GET 127.0.0.1:8080/db/user/record?uname=evanp, you will get:

[
    {
    
    
        "id": 1,
        "uname": "evanp",
        "passwd": "iloveu"
    }
]

change

Next, we modify the passwd of the uname=evanp record to 123456

app.post('/db/:tbname/record', async function (req, res) {
    
    
    //前端携带query: uname=evanp
    /*前端请求体格式:
    {
        "passwd": "123456"
    }
    */
   let resultSet = null;
    try {
    
    
        // select a record where uname=xxx
        resultSet = await sqlite(req.params.tbname).update(req.body).where('uname',req.query.uname);
        // Finally, add a catch statement
      } catch(e) {
    
    
        console.error(e);
        resultSet = e;
    };
    res.json(resultSet);
});

Try to use the api debugging tool to POST 127.0.0.1:8080/db/user/record?uname=evanp, and carry the corresponding request body, you will get: [1], which means that 1 record is affected, and it is successful

delete

Next, we delete the record of uname=evanp and passwd=123456

app.delete('/db/:tbname/record', async function (req, res) {
    
    
    /*前端请求体格式:
    {
        "uname": "evanp",
        "passwd": "123456"
    }
    */
   let resultSet = null;
    try {
    
    
        // select a record where uname=xxx
        resultSet = await sqlite(req.params.tbname).del().where(req.body);
        // Finally, add a catch statement
      } catch(e) {
    
    
        console.error(e);
        resultSet = e;
    };
    res.json(resultSet);
});

Try to use the api debugging tool DELETE 127.0.0.1:8080/db/user/record, and carry the corresponding request body, you will get: [1], which means 1 affected record, successful

native sql

Of course, if you need to use the sql statement directly, it is also possible, just call it raw(sqlStr), it can be used as a binding of a certain sql, or directly as a whole sql

Format:knex.raw(sql, [bindings]

sqlite.raw("select * from user",[1]).then((resp)=>{
    
    //..})

no introduction here

Summarize

The basic operations of using knex to add, delete, modify and check are given above. These methods are not unique. In actual development, more complex scenarios are often dealt with. The basic crud is far from enough. For more extended use methods of knex,
please Move to knex official documentation https://knexjs.org/guide/

Next section - Sql-ORM addition, deletion, modification and query

Guess you like

Origin blog.csdn.net/m0_51810668/article/details/131277990