|
| 1 | +/** |
| 2 | + * The types are explicity for learning purpose |
| 3 | + * By extending the `RowDataPacket`, you can use your Interface in `query` and `execute` |
| 4 | + */ |
| 5 | + |
| 6 | +import mysql, { |
| 7 | + ConnectionOptions, |
| 8 | + ResultSetHeader, |
| 9 | + RowDataPacket, |
| 10 | +} from 'mysql2/promise'; |
| 11 | + |
| 12 | + interface User extends RowDataPacket { |
| 13 | + /** id */ |
| 14 | + 0: number; |
| 15 | + /** name */ |
| 16 | + 1: string; |
| 17 | + } |
| 18 | + |
| 19 | +(async () => { |
| 20 | + const access: ConnectionOptions = { |
| 21 | + host: '', |
| 22 | + user: '', |
| 23 | + password: '', |
| 24 | + database: '', |
| 25 | + multipleStatements: true, |
| 26 | + }; |
| 27 | + |
| 28 | + const conn = await mysql.createConnection(access); |
| 29 | + |
| 30 | + /** Deleting the `users` table, if it exists */ |
| 31 | + await conn.query<ResultSetHeader>('DROP TABLE IF EXISTS `users`;'); |
| 32 | + |
| 33 | + /** Creating a minimal user table */ |
| 34 | + await conn.query<ResultSetHeader>( |
| 35 | + 'CREATE TABLE `users` (`id` INT(11) AUTO_INCREMENT, `name` VARCHAR(50), PRIMARY KEY (`id`));', |
| 36 | + ); |
| 37 | + |
| 38 | + /** Inserting some users */ |
| 39 | + const [inserted] = await conn.execute<ResultSetHeader>( |
| 40 | + 'INSERT INTO `users`(`name`) VALUES(?), (?), (?), (?);', |
| 41 | + ['Josh', 'John', 'Marie', 'Gween'], |
| 42 | + ); |
| 43 | + |
| 44 | + console.log('Inserted:', inserted.affectedRows); |
| 45 | + |
| 46 | + /** Getting users */ |
| 47 | + const [rows] = await conn.query<User[][]>( |
| 48 | + [ |
| 49 | + 'SELECT * FROM `users` ORDER BY `name` ASC LIMIT 2;', |
| 50 | + 'SELECT * FROM `users` ORDER BY `name` ASC LIMIT 2 OFFSET 2;', |
| 51 | + ].join(' '), |
| 52 | + ); |
| 53 | + |
| 54 | + rows.forEach((users) => { |
| 55 | + users.forEach((user) => { |
| 56 | + console.log('-----------'); |
| 57 | + console.log('id: ', user.id); |
| 58 | + console.log('name:', user.name); |
| 59 | + }); |
| 60 | + }); |
| 61 | + |
| 62 | + await conn.end(); |
| 63 | +})(); |
| 64 | + |
| 65 | +/** Output |
| 66 | + * |
| 67 | + * Inserted: 4 |
| 68 | + * ----------- |
| 69 | + * id: 4 |
| 70 | + * name: Gween |
| 71 | + * ----------- |
| 72 | + * id: 2 |
| 73 | + * name: John |
| 74 | + * ----------- |
| 75 | + * id: 1 |
| 76 | + * name: Josh |
| 77 | + * ----------- |
| 78 | + * id: 3 |
| 79 | + * name: Marie |
| 80 | + */ |
0 commit comments