Introduction To MySQL
Introduction To MySQL
1
1.3 3. Creating a Basic MySQL Database
1. Create a Database:
• Right-click on the server node and select Create New → Database.
• Enter the name for the database (e.g., yourname lab db).
• Select the character set (utf8mb4) and collation (utf8mb4 unicode ci),
then click OK.
2. Create a Table:
• Right-click on the newly created database and select Create New
→ Table.
• Set the table name (e.g., students).
• Add fields such as:
– id (INT, Primary Key, Auto Increment)
– name (VARCHAR(100))
– email (VARCHAR(100), unique)
– created at (TIMESTAMP, Default = CURRENT TIMESTAMP)
• Insert Data:
1 INSERT INTO students ( name , email ) VALUES ( ’ John Doe ’ , ’
john@example . com ’) ;
2
• Select Data:
1 SELECT * FROM students ;
2
• Update Data:
1 UPDATE students SET email = ’ j oh n do e@ ex a mp le . com ’ WHERE id =
1;
2
• Delete Data:
1 DELETE FROM students WHERE id = 1;
2
2
2 Using the Database in a Node.js, Express.js,
and EJS Project
2.1 1. Install Required Packages
In the root of your Node.js project, run:
1 npm install mysql2 express ejs
3
21
22 app . post ( ’/ delete /: id ’ , ( req , res ) = > {
23 const { id } = req . params ;
24 db . query ( ’ DELETE FROM students WHERE id = ? ’ , [ id ] , ( err ,
results ) = > {
25 if ( err ) throw err ;
26 res . redirect ( ’/ ’) ;
27 }) ;
28 }) ;
29
30 app . listen (3000 , () = > {
31 console . log ( ’ Server running on port 3000 ’) ;
32 }) ;
3 Key Takeaways
• HeidiSQL is used to interact with MySQL databases graphically.
• Basic Queries: INSERT, SELECT, UPDATE, DELETE.
• Integration with Node.js: You can connect and interact with MySQL
databases using the mysql2 package.
4
• Express.js and EJS: Create routes and dynamic HTML views for handling
and displaying database records.