-
Notifications
You must be signed in to change notification settings - Fork 13
/
2-db-callback.js
72 lines (61 loc) · 1.57 KB
/
2-db-callback.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
const fs = require('fs');
const mysql = require('mysql');
const CONNECTION_CONFIG = {
host: 'localhost',
user: 'hyfuser',
password: 'hyfpassword',
database: 'class17',
};
const CREATE_STUDENTS_TABLE = `
CREATE TABLE IF NOT EXISTS students (
student_number INT,
student_name VARCHAR(50),
date_of_birth DATE,
grade FLOAT,
gender ENUM('m', 'f')
);`;
const CREATE_TEACHERS_TABLE = `
CREATE TABLE IF NOT EXISTS teachers (
teacher_number INT,
teacher_name VARCHAR(50),
date_of_birth DATE,
subject TEXT,
gender ENUM('m', 'f')
);`;
function exitWithError(connection, err) {
console.error(err.message);
connection.end();
process.exit(1);
}
function seedDatabase() {
const connection = mysql.createConnection(CONNECTION_CONFIG);
connection.query(CREATE_STUDENTS_TABLE, err => {
if (err) {
exitWithError(connection, err);
}
connection.query(CREATE_TEACHERS_TABLE, err => {
if (err) {
exitWithError(connection, err);
}
fs.readFile(__dirname + '/students.json', 'utf8', (err, data) => {
if (err) {
exitWithError(connection, err);
}
const students = JSON.parse(data);
let count = students.length;
students.forEach(student => {
connection.query('INSERT INTO students SET ?', student, err => {
if (err) {
exitWithError(connection, err);
}
count--;
if (count === 0) {
connection.end();
}
});
});
});
});
});
}
seedDatabase();