Skip to main content

基本自定义类

¥Basic Custom Class

/**

* The types are explicity for learning purpose
*/

import { PoolOptions } from 'mysql2/promise';
import { MySQL } from './db.js';

interface User extends RowDataPacket {
id: number;
name: string;
}

const access: PoolOptions = {
host: '',
user: '',
password: '',
database: '',
};

(async () => {
const mysql = new MySQL(access);

/** Deleting the `users` table, if it exists */
await mysql.queryResult('DROP TABLE IF EXISTS `users`;');

/** Creating a minimal user table */
await mysql.queryResult(
'CREATE TABLE `users` (`id` INT(11) AUTO_INCREMENT, `name` VARCHAR(50), PRIMARY KEY (`id`));'
);

/** Inserting some users */
const [inserted] = await mysql.executeResult(
'INSERT INTO `users`(`name`) VALUES(?), (?), (?), (?);',
['Josh', 'John', 'Marie', 'Gween']
);

console.log('Inserted:', inserted.affectedRows);

/** Getting users */
const [users] = await mysql.queryRows(
'SELECT * FROM `users` ORDER BY `name` ASC;'
);

users.forEach((user: User) => {
console.log('-----------');
console.log('id: ', user.id);
console.log('name:', user.name);
});

await mysql.connection.end();
})();

/** Output

* * Inserted: 4

* -----------

* id: 4

* name: Gween

* -----------

* id: 2

* name: John

* -----------

* id: 1

* name: Josh

* -----------

* id: 3

* name: Marie
*/