forked from remarcmij/database_examples
-
Notifications
You must be signed in to change notification settings - Fork 5
/
1-db-naive.js
64 lines (54 loc) · 1.38 KB
/
1-db-naive.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
const fs = require('fs');
const mysql = require('mysql');
const CONNECTION_CONFIG = {
host: 'localhost',
user: 'hyfuser',
password: 'hyfpassword',
database: 'userdb',
};
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 seedDatabase() {
const connection = mysql.createConnection(CONNECTION_CONFIG);
connection.query(CREATE_STUDENTS_TABLE, error => {
if (error) {
throw error;
}
});
connection.query(CREATE_TEACHERS_TABLE, error => {
if (error) {
throw error;
}
});
// __dirname contains the directory in which this script is present
// The following line expects students.json in the same directory
fs.readFile(__dirname + '/students.json', 'utf8', (error, data) => {
if (error) {
throw error;
}
const students = JSON.parse(data);
for (let i = 0; i < students.length; i++) {
connection.query('INSERT INTO students SET ?', students[i], error => {
if (error) {
throw error;
}
});
}
});
connection.end();
}
seedDatabase();