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