Nodejs开发环境中基于sequelize对mysql基本操作的简单实例

Nodejs开发环境中基于sequelize对mysql基本操作的简单实例

注:以下代码经过测试,但不能保证在其他node.js环境中也能正常运行。

sequelize documents : http://sequelizejs.com/ [墙]

npm install sequelize
// 链接
var Sequelize = require('sequelize');
var sequelize = new Sequelize('nodejs', 'root', '', {host : '127.0.0.1', port : '3306', dialect : 'mysql'});
// definition
var Task = sequelize.define('Task', {
    // auto increment, primaryKey, unique
    id : {type : Sequelize.INTEGER, autoIncrement : true, primaryKey : true, unique : true},
// comment
title : {type : Sequelize.STRING, comment : 'Task title'},

// allow null
description : {type : Sequelize.TEXT, allowNull : true},

// default value
deadline : {type : Sequelize.DATE, defaultValue : Sequelize.NOW}

});

Task.sync().on(‘success’, function(){
console.log(‘aa…’);
}).on(‘failure’, function(){
console.log(‘bb…’);
});
// sequelize.query(‘your query’, [, callee], [, options], [, replacements])
// Callee is the model definition. This allows you to easily map a query to a predefined model for sequelizejs
// Options is an object with the following keys:
// {
//  logging: console.log, a function (or false) for logging your queries
//  plain: false,  if plain is true, then sequelize will return all of the records within an array, otherwise it will return a single object/first record returned.
//  raw: false,    Set this to true if you don’t have a model definition for your query
// }
// Replacements is a simple array that replaces all of the bindings within your query
sequelize.query(‘select * from user  where title = ? and description = ?’, null, {logging : true, plain : true,  raw : true}, [‘test_title_1’, ‘test_description_1’]).success(function(res){
console.log(res);
});
// find
Task.findAll({limit : 10, order : ‘id asc’}, {raw : true, logging : true, plain : false}).on(‘success’, function(res){
console.log(res);
}).on(‘failure’, function(err){
console.log(err);
})
// count
Task.count({where : {title : ‘test_title_1’}}, {logging : false}).on(‘success’, function(i){
console.log(i);
}).on(‘failure’, function(err){
console.log(err);
});
// max or min
Task.max(‘id’).on(‘success’, function(max){
console.log(max);
}).on(‘failure’, function(err){
console.log(err);
});
// insert
Task.build({title : ‘test_title_3’, ‘description’ : ‘test_description_3’}).save().on(‘success’, function(msg){
console.log(msg);
}).on(‘failure’, function(err){
console.log(err);
});

Task.create({title : ‘test_title_4’, ‘description’ : ‘test_description_4’}).on(‘success’, function(msg){ console.log(msg); }).on(‘failure’, function(err){ console.log(err); });

// update
Task.update({description : ‘test_description_2000’}, {id : ‘2’}).on(‘success’, function(msg){
console.log(msg);
}).on(‘failure’, function(err){
console.log(err);
});
// delete
Task.destroy({id : ‘4’}).on(‘success’, function(msg){
console.log(msg);
}).on(‘failure’, function(err){
console.log(err);
});


6 回复

Nodejs开发环境中基于sequelize对mysql基本操作的简单实例

在本文中,我们将展示如何在Node.js环境下使用Sequelize ORM来操作MySQL数据库。Sequelize是一个强大的Node.js库,它提供了对多种关系型数据库的访问支持,包括MySQL。

安装Sequelize

首先,你需要安装Sequelize及其依赖项:

npm install sequelize
npm install mysql2

连接到MySQL数据库

接下来,我们需要创建一个Sequelize实例来连接到MySQL数据库:

var Sequelize = require('sequelize');
var sequelize = new Sequelize('nodejs', 'root', '', {
    host: '127.0.0.1',
    port: '3306',
    dialect: 'mysql'
});

这里我们使用了root用户并连接到了本地MySQL数据库。

定义模型

定义一个Task模型,用于表示任务表中的数据:

var Task = sequelize.define('Task', {
    id: { 
        type: Sequelize.INTEGER, 
        autoIncrement: true, 
        primaryKey: true, 
        unique: true 
    },
    title: { 
        type: Sequelize.STRING, 
        comment: 'Task title' 
    },
    description: { 
        type: Sequelize.TEXT, 
        allowNull: true 
    },
    deadline: { 
        type: Sequelize.DATE, 
        defaultValue: Sequelize.NOW 
    }
});

同步模型

同步模型以确保数据库表结构与定义一致:

Task.sync().on('success', function() {
    console.log('Model has been synchronized successfully.');
}).on('failure', function(error) {
    console.log('Failed to synchronize model:', error);
});

基本查询

执行SQL查询并映射到预定义的模型:

sequelize.query(
    'SELECT * FROM Task WHERE title = ? AND description = ?', 
    null, 
    {logging: true, plain: true, raw: true}, 
    ['test_title_1', 'test_description_1']
).then(function(res) {
    console.log(res);
});

查询所有记录

获取所有任务记录:

Task.findAll({
    limit: 10,
    order: 'id ASC'
}, {
    raw: true,
    logging: true,
    plain: false
}).then(function(res) {
    console.log(res);
});

计数记录

统计满足条件的任务数量:

Task.count({
    where: {title: 'test_title_1'}
}, {
    logging: false
}).then(function(count) {
    console.log(count);
});

最大值或最小值

获取最大ID:

Task.max('id').then(function(maxId) {
    console.log(maxId);
});

插入记录

插入新任务记录:

Task.create({
    title: 'test_title_4',
    description: 'test_description_4'
}).then(function(task) {
    console.log(task);
});

更新记录

更新特定任务的描述:

Task.update({
    description: 'test_description_2000'
}, {
    where: {id: 2}
}).then(function(msg) {
    console.log(msg);
});

删除记录

删除特定任务记录:

Task.destroy({
    where: {id: 4}
}).then(function(msg) {
    console.log(msg);
});

以上就是使用Sequelize在Node.js环境中进行MySQL基本操作的简单示例。希望这些示例代码能够帮助你更好地理解和使用Sequelize。


主外建是怎么用的,不会用,请指导

Task is ready. Project is another.

Task.belongsTo(Project); Project.hasMany(Task);

如果用promise方式调用呢

请教下,如果外键不是主表的主键怎么弄呢? 比如 表user{ id, //主键 code, } 表 订单 order{ id, userCode,//用户编码 } user.hasMany(order, {foreignKey:‘userCode’, targetKey:‘code’, as:‘orders’}); 这样最终的sql依然是 以user id为主键,即:user.id = order.userCode 而实际上应该要 user.code = order.userCode

在Node.js开发环境中使用Sequelize库对MySQL数据库进行基本操作是一个常见的需求。Sequelize是一个基于Promise的ORM(对象关系映射)库,支持多种数据库,包括MySQL。下面提供一个简单的示例来展示如何使用Sequelize进行CRUD(创建、读取、更新、删除)操作。

安装依赖

首先,确保安装了sequelizemysql2包:

npm install sequelize mysql2

连接数据库

接下来是连接到MySQL数据库的代码示例:

const Sequelize = require('sequelize');

const sequelize = new Sequelize('nodejs', 'root', '', {
    host: 'localhost',
    dialect: 'mysql'
});

定义模型

定义一个Task模型:

const Task = sequelize.define('Task', {
    id: {
        type: Sequelize.INTEGER,
        autoIncrement: true,
        primaryKey: true,
        unique: true
    },
    title: {
        type: Sequelize.STRING,
        comment: 'Task title'
    },
    description: {
        type: Sequelize.TEXT,
        allowNull: true
    },
    deadline: {
        type: Sequelize.DATE,
        defaultValue: Sequelize.NOW
    }
});

同步模型

同步模型以确保数据库表结构与定义一致:

Task.sync().then(() => {
    console.log('Model synced successfully');
}).catch((error) => {
    console.error('Error syncing model:', error);
});

基本操作

查询数据

Task.findAll({
    limit: 10,
    order: 'id asc'
}).then(tasks => {
    console.log(tasks);
}).catch(error => {
    console.error('Error fetching tasks:', error);
});

插入数据

Task.create({
    title: 'test_title',
    description: 'test_description'
}).then(task => {
    console.log(task);
}).catch(error => {
    console.error('Error creating task:', error);
});

更新数据

Task.update(
    { description: 'updated_description' },
    { where: { id: 1 } }
).then(result => {
    console.log(`Rows updated: ${result[0]}`);
}).catch(error => {
    console.error('Error updating task:', error);
});

删除数据

Task.destroy({
    where: { id: 1 }
}).then(rowsDeleted => {
    console.log(`Rows deleted: ${rowsDeleted}`);
}).catch(error => {
    console.error('Error deleting task:', error);
});

这些示例展示了如何使用Sequelize进行基本的数据库操作。每个操作都通过Promise处理结果,使得代码更加简洁易读。希望这对你有所帮助!

回到顶部