Chuỗi kết nối mysql nodejs

Ngoài SQLite ra thì còn có rất nhiều hệ thống quản trị cơ sở dữ liệu nổi tiếng và mạnh mẽ, và ứng với mỗi hệ thống quản trị CSDL thì lại có vài module được sử dụng để tương tác với CSDL đó từ Node. Trong đó có một số mô-đun cung cấp các chức năng ở mức cao và cung cấp khả năng sử dụng chỉ một mô hình cho nhiều cơ sở dữ liệu khác nhau

Phần tiếp theo của mô-đun (http. // sắp xếp lại. com/) can connect tới 3 hệ thống quản trị cơ sở dữ liệu là SQLite3, MySQL và PostgreSQL. Các thao tác với cơ sở dữ liệu sẽ được thực hiện theo ORM (Ánh xạ quan hệ đối tượng)

mysql

MySQL là một hệ thống quản trị cơ sở dữ liệu SQL rất mạnh và miễn phí. Nếu bạn đã cài đặt MySQL trong máy rồi thì bạn chỉ cần tạo một cơ sở dữ liệu có tên là

var Sequelize = require('sequelize');
1 (không tạo bảng) rồi có thể bỏ qua phần này và kéo xuống phần tạo mô hình bên dưới. Nếu chưa thì bạn lên trang chủ của MySQL và tải bản Community về tại địa chỉ http. // nhà phát triển. mysql. com/tải xuống/. MySQL là một hệ thống quản trị cơ sở dữ liệu, phần cốt lõi chịu trách nhiệm lưu trữ, đọc/ghi dữ liệu… tất cả đều được thực hiện thông qua dòng lệnh, hãy làm điều đó nếu bạn muốn tải thêm phần mềm MySQL Workbench về,

Chuỗi kết nối mysql nodejs
Chuỗi kết nối mysql nodejs

Quá trình cài đặt MySQL rất đơn giản, bạn chỉ cần lưu một số thứ như tên tải khoản truy cập, thường là root, mật khẩu, chế độ cài đặt (Development, Deploy…)…

Sau khi cài đặt xong, chúng ta có thẻ bắt đầu truy cập máy chủ của MySQL để tạo cơ sở dữ liệu. Ở đây mình dùng MySQL Workbench cho nhanh. Khi mở MySQL Workbench lên, bạn sẽ phải tạo những cái gọi là Connections, nếu bạn chưa từng làm việc với Connection thì có thể cấu hình những dung lượng này giống như các nút để chúng ta thực hiện kết nối đến máy chủ vậy. Để tạo một kết nối, chúng ta nhấp vào nút dấu + phía bên trái màn hình, sau đó nhập các thông tin như tên kết nối, máy chủ là 127. 0. 0. 1, cổng là 3306, tên người dùng là tên đăng nhập mà bạn tạo khi cài đặt MySQL, vậy là xong

Chuỗi kết nối mysql nodejs
Chuỗi kết nối mysql nodejs

Sau đó, bạn nhấp vào Ok để tạo, bây giờ bên màn hình sẽ xuất hiện một nút Kết nối và chúng ta có thể nhấp vào để đăng nhập vào máy chủ. Khi đăng nhập, MySQL Workbench sẽ hỏi mật khẩu, bạn nhập mật khẩu khi cài đặt MySQL là xong

Chuỗi kết nối mysql nodejs
Chuỗi kết nối mysql nodejs

Tiếp theo chúng ta phải tạo một cơ sở dữ liệu để lưu các ghi chú cho ứng dụng Ghi chú. Bạn bấm vào nút có hình trụ với dấu + để tạo, trong này chúng tôi cần cung cấp nên CSDL và đối chiếu là tập ký tự, chúng tôi sẽ chọn là

var Sequelize = require('sequelize');
2. Ở đây chúng ta không tạo bảng vì module Sequelize sẽ tự động tạo các bảng đó cho chúng ta. Do đó quá trình tạo CSDL đã hoàn thành, bây giờ chúng ta sẽ tạo mdel

Chuỗi kết nối mysql nodejs
Chuỗi kết nối mysql nodejs

Tạo mô hình

Chúng ta tạo một thư mục mới có tên

var Sequelize = require('sequelize');
3 trong thư mục gốc của dự án, trong thư mục này chúng ta tạo một tệp có tên
var Sequelize = require('sequelize');
4 với nội dung như sau

var Sequelize = require('sequelize');
var Note = undefined;
module.exports.connect = function(params, callback) {
    var sequlz = new Sequelize(
        params.dbname, 
        params.username, 
        params.password,
        params.params
    );
    Note = sequlz.define('Note', {
        notekey: {
            type: Sequelize.STRING,
            primaryKey: true,
            unique: true
        },
        title: Sequelize.STRING,
        body: Sequelize.TEXT
    });
    Note.sync().then(function() {
        callback();
    }).error(function(err) {
        callback(err);
    });
}
exports.disconnect = function(callback) {
    callback();
}

exports.create = function(key, title, body, callback) {
    Note.create({
            notekey: key,
            title: title,
            body: body
        }).then(function(note) {
            callback();
        }).error(function(err) {
            callback(err);
    });
}

exports.update = function(key, title, body, callback) {
    Note.find({ where:{ notekey: key} }).then(function(note) {
        if(!note) {
            callback(new Error("No note found for key " + key));
        } else {
            note.updateAttributes({
                title: title,
                body: body
            }).then(function() { 
                callback();
            }).error(function(err) {
                callback(err);
            });
        }
    }).error(function(err) {
        callback(err);
    });
}

exports.read = function(key, callback) {
    Note.find({ where:{ notekey: key} }).then(function(note) {
        if(!note) {
            callback("Nothing found for " + key);
        } else {
            callback(null, {
                notekey: note.notekey,
                title: note.title,
                body: note.body
            });
        }
    });
}

exports.destroy = function(key, callback) {
    Note.find({ where:{ notekey: key} }).then(function(note) {
        note.destroy().then(function() {
        callback();
    }).error(function(err) {
        callback(err);
    });
    });
}

exports.titles = function(callback) { 
    Note.findAll().then(function(notes) { 
        var noteList = []; 
        notes.forEach(function(note) { 
            noteList.push({
                key: note.notekey,
                title: note.title
            }); 
        });
        callback(null, noteList);
    });
}

Cũng giống như các phần trước, tập tin này sẽ lưu trữ phần mô hình của ứng dụng

var Sequelize = require('sequelize');

Chúng ta sẽ cần sử dụng đến mô-đun

var Sequelize = require('sequelize');
5

var Note = undefined;
module.exports.connect = function(params, callback) {
    var sequlz = new Sequelize(
        params.dbname, 
        params.username, 
        params.password,
        params.params
    );
    Note = sequlz.define('Note', {
        notekey: {
            type: Sequelize.STRING,
            primaryKey: true,
            unique: true
        },
        title: Sequelize.STRING,
        body: Sequelize.TEXT
    });
    Note.sync().then(function() {
        callback();
    }).error(function(err) {
        callback(err);
    });
}
exports.disconnect = function(callback) {
    callback();
}

Ở đây hàm

var Sequelize = require('sequelize');
6 không nhận vào một chuỗi thông thường như các phần trước mà sẽ nhận vào một tập tham số, bao gồm tên cơ sở dữ liệu (
var Sequelize = require('sequelize');
7)
var Sequelize = require('sequelize');
8 tên đăng nhập (
var Sequelize = require('sequelize');
9)
var Sequelize = require('sequelize');
8 mật khẩu (
var Note = undefined;
module.exports.connect = function(params, callback) {
    var sequlz = new Sequelize(
        params.dbname, 
        params.username, 
        params.password,
        params.params
    );
    Note = sequlz.define('Note', {
        notekey: {
            type: Sequelize.STRING,
            primaryKey: true,
            unique: true
        },
        title: Sequelize.STRING,
        body: Sequelize.TEXT
    });
    Note.sync().then(function() {
        callback();
    }).error(function(err) {
        callback(err);
    });
}
exports.disconnect = function(callback) {
    callback();
}
1)
var Sequelize = require('sequelize');
8 địa chỉ máy chủ MySQL

Như đã nói ở trên, chúng ta không tạo bảng một cách trực tiếp mà phần tiếp theo sẽ tạo các bảng đó cho chúng ta, bằng cách sử dụng phương thức

var Note = undefined;
module.exports.connect = function(params, callback) {
    var sequlz = new Sequelize(
        params.dbname, 
        params.username, 
        params.password,
        params.params
    );
    Note = sequlz.define('Note', {
        notekey: {
            type: Sequelize.STRING,
            primaryKey: true,
            unique: true
        },
        title: Sequelize.STRING,
        body: Sequelize.TEXT
    });
    Note.sync().then(function() {
        callback();
    }).error(function(err) {
        callback(err);
    });
}
exports.disconnect = function(callback) {
    callback();
}
5tham số đầu tiên là bảng tên, ở đây mình đặt là Ghi chú, phần tiếp theo sẽ tạo bảng . Phương thức
var Sequelize = require('sequelize');
20 sẽ thực hiện việc tạo sự thật trên cơ sở dữ liệu

var Sequelize = require('sequelize');
2

Hàm

var Sequelize = require('sequelize');
21 sẽ thực hiện việc tạo các bản ghi mới. Để chèn một bản ghi, chúng ta chỉ cần gọi phương thức
var Sequelize = require('sequelize');
22 và đưa các tham số tương ứng vào, sau đó gọi hàm
var Sequelize = require('sequelize');
23 ngoài hàm còn hàm
var Sequelize = require('sequelize');
24 có chức năng kiểm tra xem có lỗi hay không

var Sequelize = require('sequelize');
8

Hàm

var Sequelize = require('sequelize');
25 sẽ cập nhật các ghi chú. Ở đây thao tác cập nhật hơi khác chút xíu. Đầu tiên chúng ta phải tìm bản ghi đó bằng phương thức
var Sequelize = require('sequelize');
26 phương thức này tiếp nhận câu truy vấn, bạn có thể xem cấu trúc truy vấn theo đoạn mã trên. Sau đó gọi hàm
var Sequelize = require('sequelize');
23 hàm này nhận vào hàm gọi lại và hàm gọi lại hàm này nhận dữ liệu trả về. Chúng ta có thể kiểm tra xem dữ liệu trả về này có trống hay không, nếu không trống thì chúng ta thực hiện cập nhật dữ liệu mới này bằng cách gọi hàm
var Sequelize = require('sequelize');
28

var Sequelize = require('sequelize');
3

Hàm

var Sequelize = require('sequelize');
29 được dùng để đọc ghi chú và cũng tương tự như hàm
var Sequelize = require('sequelize');
80

var Sequelize = require('sequelize');
6

Hàm

var Sequelize = require('sequelize');
81 được dùng để xóa một ghi chú, tương tự như vậy chúng ta cũng tìm một ghi chú trước và nếu thấy thì chúng ta xóa ghi chú đó bằng hàm
var Sequelize = require('sequelize');
82

var Sequelize = require('sequelize');
9

Hàm

var Sequelize = require('sequelize');
83 sẽ liệt kê toàn bộ bộ ghi chú có trong CSDL, để lấy về toàn bộ bộ ghi chú thì chúng ta dùng hàm
var Sequelize = require('sequelize');
84

Cấu hình ứng dụng. js

Trong tệp

var Sequelize = require('sequelize');
85 chúng ta sửa lại như sau

var Sequelize = require('sequelize');
var Note = undefined;
module.exports.connect = function(params, callback) {
    var sequlz = new Sequelize(
        params.dbname, 
        params.username, 
        params.password,
        params.params
    );
    Note = sequlz.define('Note', {
        notekey: {
            type: Sequelize.STRING,
            primaryKey: true,
            unique: true
        },
        title: Sequelize.STRING,
        body: Sequelize.TEXT
    });
    Note.sync().then(function() {
        callback();
    }).error(function(err) {
        callback(err);
    });
}
exports.disconnect = function(callback) {
    callback();
}

exports.create = function(key, title, body, callback) {
    Note.create({
            notekey: key,
            title: title,
            body: body
        }).then(function(note) {
            callback();
        }).error(function(err) {
            callback(err);
    });
}

exports.update = function(key, title, body, callback) {
    Note.find({ where:{ notekey: key} }).then(function(note) {
        if(!note) {
            callback(new Error("No note found for key " + key));
        } else {
            note.updateAttributes({
                title: title,
                body: body
            }).then(function() { 
                callback();
            }).error(function(err) {
                callback(err);
            });
        }
    }).error(function(err) {
        callback(err);
    });
}

exports.read = function(key, callback) {
    Note.find({ where:{ notekey: key} }).then(function(note) {
        if(!note) {
            callback("Nothing found for " + key);
        } else {
            callback(null, {
                notekey: note.notekey,
                title: note.title,
                body: note.body
            });
        }
    });
}

exports.destroy = function(key, callback) {
    Note.find({ where:{ notekey: key} }).then(function(note) {
        note.destroy().then(function() {
        callback();
    }).error(function(err) {
        callback(err);
    });
    });
}

exports.titles = function(callback) { 
    Note.findAll().then(function(notes) { 
        var noteList = []; 
        notes.forEach(function(note) { 
            noteList.push({
                key: note.notekey,
                title: note.title
            }); 
        });
        callback(null, noteList);
    });
}
3

Ở đây chúng ta lưu ý là tham số để kết nối tới CSDL là một số tham số tập tin như địa chỉ, tên người dùng, mật khẩu đăng nhập… bạn điền cho chính xác là được

Tiếp theo chúng ta khai báo mô-đun

var Sequelize = require('sequelize');
86 trong tệp
var Sequelize = require('sequelize');
87 như sau

var Sequelize = require('sequelize');
var Note = undefined;
module.exports.connect = function(params, callback) {
    var sequlz = new Sequelize(
        params.dbname, 
        params.username, 
        params.password,
        params.params
    );
    Note = sequlz.define('Note', {
        notekey: {
            type: Sequelize.STRING,
            primaryKey: true,
            unique: true
        },
        title: Sequelize.STRING,
        body: Sequelize.TEXT
    });
    Note.sync().then(function() {
        callback();
    }).error(function(err) {
        callback(err);
    });
}
exports.disconnect = function(callback) {
    callback();
}

exports.create = function(key, title, body, callback) {
    Note.create({
            notekey: key,
            title: title,
            body: body
        }).then(function(note) {
            callback();
        }).error(function(err) {
            callback(err);
    });
}

exports.update = function(key, title, body, callback) {
    Note.find({ where:{ notekey: key} }).then(function(note) {
        if(!note) {
            callback(new Error("No note found for key " + key));
        } else {
            note.updateAttributes({
                title: title,
                body: body
            }).then(function() { 
                callback();
            }).error(function(err) {
                callback(err);
            });
        }
    }).error(function(err) {
        callback(err);
    });
}

exports.read = function(key, callback) {
    Note.find({ where:{ notekey: key} }).then(function(note) {
        if(!note) {
            callback("Nothing found for " + key);
        } else {
            callback(null, {
                notekey: note.notekey,
                title: note.title,
                body: note.body
            });
        }
    });
}

exports.destroy = function(key, callback) {
    Note.find({ where:{ notekey: key} }).then(function(note) {
        note.destroy().then(function() {
        callback();
    }).error(function(err) {
        callback(err);
    });
    });
}

exports.titles = function(callback) { 
    Note.findAll().then(function(notes) { 
        var noteList = []; 
        notes.forEach(function(note) { 
            noteList.push({
                key: note.notekey,
                title: note.title
            }); 
        });
        callback(null, noteList);
    });
}
6

Cuối cùng chúng ta chạy lệnh

var Sequelize = require('sequelize');
88 để cài đặt mô-đun này rồi chạy
var Sequelize = require('sequelize');
89 để chạy máy chủ xong