new sql.Database(driverName: string, dataSourceName: string) method can be called to establish a database connection. Where, driverNamedataSourceName specifies the data source.import sql from 'pts/sql';const db = new sql.Database(sql.MySQL, "user:passwd@tcp(ip:port)/database")export default function () {// Send a request to the database.}
user:passwd@tcp(ip:port)/database?parseTime=true) in the connection string when establishing the database connection to avoid time parsing errors.db.query(sql string) method can be called for SQL query, which returns an array of database records that meet the conditions. Where, sql specifies the SQL query statement passed in.import sql from 'pts/sql';const db = new sql.Database(sql.MySQL, "user:passwd@tcp(ip:port)/database")export default function () {let rows = db.query("SELECT * FROM user");console.log(JSON.stringify(rows)); // [{"id":1,"name":"zhangsan","age":23},{"id":2,"name":"lisi","age":2}]}
db.exec(sql string) method can be called for SQL execution. After the execution statement is padded in, this method can return the impact of the execution on the database (return fields include the ID of the last inserted row and the number of all affected rows).sql specifies the SQL execution statement passed in.import sql from 'pts/sql';const db = new sql.Database(sql.MySQL, "user:passwd@tcp(ip:port)/database")export default function () {// Modify data.let result = db.exec("UPDATE user SET age=? WHERE name='zhangsan'", Math.floor(Math.random() * 100));console.log(JSON.stringify(result)); // {"lastInsertId":0,"rowsAffected":1}// Insert data.let result1 = db.exec("insert into user (name, age) values ('wanger', 18)");console.log(JSON.stringify(result)); // {"lastInsertId":66,"rowsAffected":1}}
db.exec method supports common DDL commands (such as create, drop, and alter) and common DML commands (such as insert, update, and delete).import sql from 'pts/sql';import { sleep, check } from 'pts';const db = new sql.Database(sql.MySQL, "user:passwd@tcp(ip:port)/database")export default function () {// Query data.let rows = db.query("SELECT * FROM user");console.log(JSON.stringify(rows)); // [{"id":1,"name":"zhangsan","age":23},{"id":2,"name":"lisi","age":2}]// Add data.let result = db.exec("insert into user (name, age) values ('wanger', 18)");console.log(JSON.stringify(result)); // {"lastInsertId":66,"rowsAffected":1}// Delete data.let result1 = db.exec("delete from user where id > 8");console.log(JSON.stringify(result)); // {"lastInsertId":0,"rowsAffected":2}// Modify data.let result2 = db.exec("UPDATE user SET age=? WHERE name='zhangsan'", Math.floor(Math.random() * 100));console.log(JSON.stringify(result)); // {"lastInsertId":0,"rowsAffected":1}// Set checkpoints.check("1 row returned", () => result.rowsAffected === 1);sleep(1)}
Feedback