Không thể tìm thấy mô-đun mysql2/lời hứa

详细错误:Unhandled promise rejection Error. đám mây. chức năng gọi. fail -404011 lỗi thực thi chức năng đám mây. 云函数执行错误

云端堆栈信息(error stack)(requestId 2836569b-b38c-11eb-848a-5254008c2339, callid 1620870011844-0. 5495294339013359)

Hãy thử cấu hình docker bên dưới cho một ứng dụng nút. Nó sẽ làm việc cho bạn

 node-app:
  container_name: node-app
  image: node:latest
  restart: always
  volumes:
   - ./:/home/node/app
  working_dir: /home/node/app
  ports:
   - 4000:4000
  networks:
   - main-network
  command: "tail -f /dev/null && npm start"

Dưới đây là gói. json

"main": "index.js",
"scripts": {
  "preinstall": "npm i nodemon -g",
  "start": "nodemon index.js",
}

Trong khi tôi viết blog về cách thiết lập Node. js và MySQL gần hai năm trước, thật thú vị khi một sinh viên gặp sự cố. Sinh viên cho biết họ đã định cấu hình môi trường nhưng không thể sử dụng Node. js để truy cập MySQL

Lỗi là do câu lệnh nhập này gây ra

const mysql = require('mysql')

const mysql = yêu cầu ('mysql')

Sinh viên gặp lỗi sau, đơn giản là họ chưa cài đặt Node. js cho trình điều khiển MySQL

internal/modules/cjs/loader.js:638
    throw err;
    ^
 
Error: Cannot find module 'mysql'
    at Function.Module._resolveFilename (internal/modules/cjs/loader.js:636:15)
    at Function.Module._load (internal/modules/cjs/loader.js:562:25)
    at Module.require (internal/modules/cjs/loader.js:692:17)
    at require (internal/modules/cjs/helpers.js:25:18)
    at Object. (/home/student/Data/cit325/oracle-s/lib/Oracle12cPLSQLCode/Introduction/query.js:4:15)
    at Module._compile (internal/modules/cjs/loader.js:778:30)
    at Object.Module._extensions..js (internal/modules/cjs/loader.js:789:10)
    at Module.load (internal/modules/cjs/loader.js:653:32)
    at tryModuleLoad (internal/modules/cjs/loader.js:593:12)
    at Function.Module._load (internal/modules/cjs/loader.js:585:3)

nội bộ/mô-đun/cjs/bộ tải. js. 638 quả ném biên; . Không thể tìm thấy mô-đun 'mysql' tại Chức năng. mô-đun. _resolveFilename (nội bộ/mô-đun/cjs/bộ tải. js. 636. 15) tại Chức năng. mô-đun. _load (nội bộ/mô-đun/cjs/bộ tải. js. 562. 25) tại Mô-đun. yêu cầu (nội bộ/mô-đun/cjs/bộ tải. js. 692. 17) theo yêu cầu (nội bộ/mô-đun/cjs/người trợ giúp. js. 25. 18) tại Đối tượng. (/home/student/Data/cit325/oracle-s/lib/Oracle12cPLSQLCode/Giới thiệu/truy vấn. js. 4. 15) tại Mô-đun. _compile (nội bộ/mô-đun/cjs/bộ tải. js. 778. 30) tại Đối tượng. mô-đun. _phần mở rộng. js (nội bộ/mô-đun/cjs/trình tải. js. 789. 10) tại Mô-đun. tải (nội bộ/mô-đun/cjs/bộ tải. js. 653. 32) tại tryModuleLoad (nội bộ/mô-đun/cjs/bộ tải. js. 593. 12) tại Chức năng. mô-đun. _load (nội bộ/mô-đun/cjs/bộ tải. js. 585. 3)

Tôi đã giải thích rằng họ có thể khắc phục sự cố với hai Nút sau. js Các lệnh Trình quản lý gói (NPM)

npm init --y 
npm install --save mysql

npm init --y npm cài đặt --save mysql

Học sinh đã có thể kiểm tra lại mã thành công. Vấn đề đơn giản là Node. js không thể tìm thấy mô-đun NPM MySQL

Phân tích sâu hơn về trạng thái bảo trì của lời hứa mysql2 dựa trên nhịp phiên bản npm đã phát hành, hoạt động của kho lưu trữ và các điểm dữ liệu khác đã xác định rằng việc bảo trì của nó là Không hoạt động

Một tín hiệu bảo trì dự án quan trọng cần xem xét đối với lời hứa mysql2 là nó không thấy bất kỳ phiên bản mới nào được phát hành cho npm trong 12 tháng qua và có thể được coi là một dự án đã ngừng hoạt động hoặc dự án ít nhận được sự quan tâm từ những người bảo trì của nó

Trong tháng trước, chúng tôi không tìm thấy bất kỳ hoạt động yêu cầu kéo nào hoặc thay đổi trạng thái vấn đề đã được phát hiện đối với kho lưu trữ GitHub

Máy khách MySQL cho Nút. js tập trung vào hiệu suất. Hỗ trợ các câu lệnh đã chuẩn bị, mã hóa không phải utf8, giao thức nhật ký nhị phân, nén, ssl nhiều hơn nữa

Mục lục

Lịch sử và Tại sao MySQL2

Dự án MySQL2 là sự tiếp nối của MySQL-Native. Mã trình phân tích cú pháp giao thức đã được viết lại từ đầu và api đã thay đổi để phù hợp với mysqljs/mysql phổ biến. Nhóm MySQL2 đang làm việc cùng với nhóm mysqljs/mysql để tìm ra mã được chia sẻ và chuyển nó vào tổ chức mysqljs

MySQL2 chủ yếu là API tương thích với mysqljs và hỗ trợ phần lớn các tính năng. MySQL2 cũng cung cấp các tính năng bổ sung này

  • Hiệu suất nhanh hơn / tốt hơn
  • báo cáo chuẩn bị
  • Giao thức nhật ký nhị phân MySQL
  • Máy chủ MySQL
  • Hỗ trợ mở rộng cho Mã hóa và Đối chiếu
  • Giấy gói lời hứa
  • Nén
  • Chuyển đổi SSL và xác thực
  • Luồng tùy chỉnh

Cài đặt

MySQL2 không có ràng buộc gốc và có thể được cài đặt trên Linux, Mac OS hoặc Windows mà không gặp bất kỳ sự cố nào

npm install --save mysql2

Truy vấn đầu tiên

// get the client
const mysql = require('mysql2');

// create the connection to database
const connection = mysql.createConnection({
  host: 'localhost',
  user: 'root',
  database: 'test'
});

// simple query
connection.query(
  'SELECT * FROM `table` WHERE `name` = "Page" AND `age` > 45',
  function(err, results, fields) {
    console.log(results); // results contains rows returned by server
    console.log(fields); // fields contains extra meta data about results, if available
  }
);

// with placeholder
connection.query(
  'SELECT * FROM `table` WHERE `name` = ? AND `age` > ?',
  ['Page', 45],
  function(err, results) {
    console.log(results);
  }
);

Sử dụng câu lệnh đã chuẩn bị

Với MySQL2, bạn cũng nhận được các câu lệnh đã chuẩn bị. Với các câu lệnh đã chuẩn bị, MySQL không phải chuẩn bị kế hoạch cho cùng một truy vấn mọi lúc, điều này dẫn đến hiệu suất tốt hơn. Nếu bạn không biết tại sao chúng lại quan trọng, vui lòng kiểm tra các cuộc thảo luận này

  • Làm thế nào các câu lệnh được chuẩn bị có thể bảo vệ khỏi các cuộc tấn công SQL Injection

MySQL cung cấp trình trợ giúp

// get the client
const mysql = require('mysql2');

// create the connection to database
const connection = mysql.createConnection({
  host: 'localhost',
  user: 'root',
  database: 'test'
});

// simple query
connection.query(
  'SELECT * FROM `table` WHERE `name` = "Page" AND `age` > 45',
  function(err, results, fields) {
    console.log(results); // results contains rows returned by server
    console.log(fields); // fields contains extra meta data about results, if available
  }
);

// with placeholder
connection.query(
  'SELECT * FROM `table` WHERE `name` = ? AND `age` > ?',
  ['Page', 45],
  function(err, results) {
    console.log(results);
  }
);
2 sẽ chuẩn bị và truy vấn câu lệnh. Bạn cũng có thể tự chuẩn bị/không chuẩn bị câu lệnh bằng các phương pháp
// get the client
const mysql = require('mysql2');

// create the connection to database
const connection = mysql.createConnection({
  host: 'localhost',
  user: 'root',
  database: 'test'
});

// simple query
connection.query(
  'SELECT * FROM `table` WHERE `name` = "Page" AND `age` > 45',
  function(err, results, fields) {
    console.log(results); // results contains rows returned by server
    console.log(fields); // fields contains extra meta data about results, if available
  }
);

// with placeholder
connection.query(
  'SELECT * FROM `table` WHERE `name` = ? AND `age` > ?',
  ['Page', 45],
  function(err, results) {
    console.log(results);
  }
);
3 /
// get the client
const mysql = require('mysql2');

// create the connection to database
const connection = mysql.createConnection({
  host: 'localhost',
  user: 'root',
  database: 'test'
});

// simple query
connection.query(
  'SELECT * FROM `table` WHERE `name` = "Page" AND `age` > 45',
  function(err, results, fields) {
    console.log(results); // results contains rows returned by server
    console.log(fields); // fields contains extra meta data about results, if available
  }
);

// with placeholder
connection.query(
  'SELECT * FROM `table` WHERE `name` = ? AND `age` > ?',
  ['Page', 45],
  function(err, results) {
    console.log(results);
  }
);
4

// get the client
const mysql = require('mysql2');

// create the connection to database
const connection = mysql.createConnection({
  host: 'localhost',
  user: 'root',
  database: 'test'
});

// execute will internally call prepare and query
connection.execute(
  'SELECT * FROM `table` WHERE `name` = ? AND `age` > ?',
  ['Rick C-137', 53],
  function(err, results, fields) {
    console.log(results); // results contains rows returned by server
    console.log(fields); // fields contains extra meta data about results, if available

    // If you execute same statement again, it will be picked from a LRU cache
    // which will save query preparation time and give better performance
  }
);

Sử dụng nhóm kết nối

Nhóm kết nối giúp giảm thời gian kết nối với máy chủ MySQL bằng cách sử dụng lại kết nối trước đó, để chúng mở thay vì đóng khi bạn hoàn thành chúng

Điều này giúp cải thiện độ trễ của các truy vấn khi bạn tránh được tất cả các chi phí đi kèm với việc thiết lập kết nối mới

// get the client
const mysql = require('mysql2');

// Create the connection pool. The pool-specific settings are the defaults
const pool = mysql.createPool({
  host: 'localhost',
  user: 'root',
  database: 'test',
  waitForConnections: true,
  connectionLimit: 10,
  queueLimit: 0
});

Nhóm không tạo tất cả các kết nối trước mà tạo chúng theo yêu cầu cho đến khi đạt đến giới hạn kết nối

Bạn có thể sử dụng nhóm theo cách tương tự như các kết nối (sử dụng

// get the client
const mysql = require('mysql2');

// create the connection to database
const connection = mysql.createConnection({
  host: 'localhost',
  user: 'root',
  database: 'test'
});

// simple query
connection.query(
  'SELECT * FROM `table` WHERE `name` = "Page" AND `age` > 45',
  function(err, results, fields) {
    console.log(results); // results contains rows returned by server
    console.log(fields); // fields contains extra meta data about results, if available
  }
);

// with placeholder
connection.query(
  'SELECT * FROM `table` WHERE `name` = ? AND `age` > ?',
  ['Page', 45],
  function(err, results) {
    console.log(results);
  }
);
5 và
// get the client
const mysql = require('mysql2');

// create the connection to database
const connection = mysql.createConnection({
  host: 'localhost',
  user: 'root',
  database: 'test'
});

// simple query
connection.query(
  'SELECT * FROM `table` WHERE `name` = "Page" AND `age` > 45',
  function(err, results, fields) {
    console.log(results); // results contains rows returned by server
    console.log(fields); // fields contains extra meta data about results, if available
  }
);

// with placeholder
connection.query(
  'SELECT * FROM `table` WHERE `name` = ? AND `age` > ?',
  ['Page', 45],
  function(err, results) {
    console.log(results);
  }
);
6)

// For pool initialization, see above
pool.query("SELECT field FROM atable", function(err, rows, fields) {
   // Connection is automatically released when query resolves
})

Ngoài ra, cũng có khả năng lấy kết nối thủ công từ nhóm và trả lại sau

// For pool initialization, see above
pool.getConnection(function(err, conn) {
   // Do something with the connection
   conn.query(/* .. */);
   // Don't forget to release the connection when finished!
   pool.releaseConnection(conn);
})

Sử dụng Promise Wrapper

MySQL2 cũng hỗ trợ Promise API. Cái nào hoạt động rất tốt với ES7 async đang chờ

async function main() {
  // get the client
  const mysql = require('mysql2/promise');
  // create the connection
  const connection = await mysql.createConnection({host:'localhost', user: 'root', database: 'test'});
  // query database
  const [rows, fields] = await connection.execute('SELECT * FROM `table` WHERE `name` = ? AND `age` > ?', ['Morty', 14]);
}

MySQL2 sử dụng đối tượng

// get the client
const mysql = require('mysql2');

// create the connection to database
const connection = mysql.createConnection({
  host: 'localhost',
  user: 'root',
  database: 'test'
});

// simple query
connection.query(
  'SELECT * FROM `table` WHERE `name` = "Page" AND `age` > 45',
  function(err, results, fields) {
    console.log(results); // results contains rows returned by server
    console.log(fields); // fields contains extra meta data about results, if available
  }
);

// with placeholder
connection.query(
  'SELECT * FROM `table` WHERE `name` = ? AND `age` > ?',
  ['Page', 45],
  function(err, results) {
    console.log(results);
  }
);
7 mặc định có sẵn trong phạm vi. Nhưng bạn có thể chọn triển khai
// get the client
const mysql = require('mysql2');

// create the connection to database
const connection = mysql.createConnection({
  host: 'localhost',
  user: 'root',
  database: 'test'
});

// simple query
connection.query(
  'SELECT * FROM `table` WHERE `name` = "Page" AND `age` > 45',
  function(err, results, fields) {
    console.log(results); // results contains rows returned by server
    console.log(fields); // fields contains extra meta data about results, if available
  }
);

// with placeholder
connection.query(
  'SELECT * FROM `table` WHERE `name` = ? AND `age` > ?',
  ['Page', 45],
  function(err, results) {
    console.log(results);
  }
);
7 mà bạn muốn sử dụng

// get the client
const mysql = require('mysql2/promise');

// get the promise implementation, we will use bluebird
const bluebird = require('bluebird');

// create the connection, specify bluebird as Promise
const connection = await mysql.createConnection({host:'localhost', user: 'root', database: 'test', Promise: bluebird});

// query database
const [rows, fields] = await connection.execute('SELECT * FROM `table` WHERE `name` = ? AND `age` > ?', ['Morty', 14]);

MySQL2 cũng cho thấy một. promise() trên Nhóm, vì vậy bạn có thể tạo kết nối hứa hẹn/không hứa hẹn từ cùng một nhóm

async function main() {
  // get the client
  const mysql = require('mysql2');
  // create the pool
  const pool = mysql.createPool({host:'localhost', user: 'root', database: 'test'});
  // now get a Promise wrapped instance of that pool
  const promisePool = pool.promise();
  // query database using promises
  const [rows,fields] = await promisePool.query("SELECT 1");

MySQL2 hiển thị một. promise() trên Kết nối, để "nâng cấp" kết nối không hứa hẹn hiện có để sử dụng lời hứa

// get the client
const mysql = require('mysql2');
// create the connection
const con = mysql.createConnection(
  {host:'localhost', user: 'root', database: 'test'}
);
con.promise().query("SELECT 1")
  .then( ([rows,fields]) => {
    console.log(rows);
  })
  .catch(console.log)
  .then( () => con.end());

Kết quả mảng

Nếu bạn có hai cột có cùng tên, bạn có thể muốn nhận kết quả dưới dạng một mảng thay vì một đối tượng để ngăn chúng xung đột. Đây là một sai lệch so với thư viện Node MySQL

Ví dụ.

// get the client
const mysql = require('mysql2');

// create the connection to database
const connection = mysql.createConnection({
  host: 'localhost',
  user: 'root',
  database: 'test'
});

// simple query
connection.query(
  'SELECT * FROM `table` WHERE `name` = "Page" AND `age` > 45',
  function(err, results, fields) {
    console.log(results); // results contains rows returned by server
    console.log(fields); // fields contains extra meta data about results, if available
  }
);

// with placeholder
connection.query(
  'SELECT * FROM `table` WHERE `name` = ? AND `age` > ?',
  ['Page', 45],
  function(err, results) {
    console.log(results);
  }
);
9

Bạn có thể bật cài đặt này ở cấp độ kết nối (áp dụng cho tất cả các truy vấn) hoặc ở cấp độ truy vấn (chỉ áp dụng cho truy vấn cụ thể đó)

Tùy chọn kết nối

// get the client
const mysql = require('mysql2');

// create the connection to database
const connection = mysql.createConnection({
  host: 'localhost',
  user: 'root',
  database: 'test'
});

// simple query
connection.query(
  'SELECT * FROM `table` WHERE `name` = "Page" AND `age` > 45',
  function(err, results, fields) {
    console.log(results); // results contains rows returned by server
    console.log(fields); // fields contains extra meta data about results, if available
  }
);

// with placeholder
connection.query(
  'SELECT * FROM `table` WHERE `name` = ? AND `age` > ?',
  ['Page', 45],
  function(err, results) {
    console.log(results);
  }
);
0

Tùy chọn truy vấn

// get the client
const mysql = require('mysql2');

// create the connection to database
const connection = mysql.createConnection({
  host: 'localhost',
  user: 'root',
  database: 'test'
});

// simple query
connection.query(
  'SELECT * FROM `table` WHERE `name` = "Page" AND `age` > 45',
  function(err, results, fields) {
    console.log(results); // results contains rows returned by server
    console.log(fields); // fields contains extra meta data about results, if available
  }
);

// with placeholder
connection.query(
  'SELECT * FROM `table` WHERE `name` = ? AND `age` > ?',
  ['Page', 45],
  function(err, results) {
    console.log(results);
  }
);
1

API và cấu hình

MySQL2 chủ yếu là API tương thích với Node MySQL. Bạn nên kiểm tra tài liệu API của họ để xem tất cả các tùy chọn API có sẵn

Một điểm không tương thích đã biết là các giá trị

// get the client
const mysql = require('mysql2');

// create the connection to database
const connection = mysql.createConnection({
  host: 'localhost',
  user: 'root',
  database: 'test'
});

// execute will internally call prepare and query
connection.execute(
  'SELECT * FROM `table` WHERE `name` = ? AND `age` > ?',
  ['Rick C-137', 53],
  function(err, results, fields) {
    console.log(results); // results contains rows returned by server
    console.log(fields); // fields contains extra meta data about results, if available

    // If you execute same statement again, it will be picked from a LRU cache
    // which will save query preparation time and give better performance
  }
);
0 được trả về dưới dạng chuỗi trong khi ở Node MySQL, chúng được trả về dưới dạng số. Điều này bao gồm kết quả của các hàm
// get the client
const mysql = require('mysql2');

// create the connection to database
const connection = mysql.createConnection({
  host: 'localhost',
  user: 'root',
  database: 'test'
});

// execute will internally call prepare and query
connection.execute(
  'SELECT * FROM `table` WHERE `name` = ? AND `age` > ?',
  ['Rick C-137', 53],
  function(err, results, fields) {
    console.log(results); // results contains rows returned by server
    console.log(fields); // fields contains extra meta data about results, if available

    // If you execute same statement again, it will be picked from a LRU cache
    // which will save query preparation time and give better performance
  }
);
1 và
// get the client
const mysql = require('mysql2');

// create the connection to database
const connection = mysql.createConnection({
  host: 'localhost',
  user: 'root',
  database: 'test'
});

// execute will internally call prepare and query
connection.execute(
  'SELECT * FROM `table` WHERE `name` = ? AND `age` > ?',
  ['Rick C-137', 53],
  function(err, results, fields) {
    console.log(results); // results contains rows returned by server
    console.log(fields); // fields contains extra meta data about results, if available

    // If you execute same statement again, it will be picked from a LRU cache
    // which will save query preparation time and give better performance
  }
);
2 khi áp dụng cho các đối số
// get the client
const mysql = require('mysql2');

// create the connection to database
const connection = mysql.createConnection({
  host: 'localhost',
  user: 'root',
  database: 'test'
});

// execute will internally call prepare and query
connection.execute(
  'SELECT * FROM `table` WHERE `name` = ? AND `age` > ?',
  ['Rick C-137', 53],
  function(err, results, fields) {
    console.log(results); // results contains rows returned by server
    console.log(fields); // fields contains extra meta data about results, if available

    // If you execute same statement again, it will be picked from a LRU cache
    // which will save query preparation time and give better performance
  }
);
3. Điều này được thực hiện có chủ ý để tránh mất độ chính xác - xem https. //github. com/sidorares/node-mysql2/issues/935

Nếu bạn tìm thấy bất kỳ sự không tương thích nào khác với Node MySQL, vui lòng báo cáo qua Trình theo dõi sự cố. Chúng tôi sẽ khắc phục sự không tương thích được báo cáo trên cơ sở ưu tiên

Tài liệu

Bạn có thể tìm thêm tài liệu chi tiết tại đây. Bạn cũng nên kiểm tra các ví dụ mã khác nhau để hiểu các khái niệm nâng cao

Sự nhìn nhận

  • Giao thức nội bộ được viết bởi @sidorares MySQL-Native
  • Các hằng số, nội suy tham số SQL, Pooling, lớp
    // get the client
    const mysql = require('mysql2');
    
    // create the connection to database
    const connection = mysql.createConnection({
      host: 'localhost',
      user: 'root',
      database: 'test'
    });
    
    // execute will internally call prepare and query
    connection.execute(
      'SELECT * FROM `table` WHERE `name` = ? AND `age` > ?',
      ['Rick C-137', 53],
      function(err, results, fields) {
        console.log(results); // results contains rows returned by server
        console.log(fields); // fields contains extra meta data about results, if available
    
        // If you execute same statement again, it will be picked from a LRU cache
        // which will save query preparation time and give better performance
      }
    );
    4 được lấy từ nút-mysql
  • Mã nâng cấp SSL dựa trên mã @TooTallNate
  • Cờ api kết nối an toàn / kết nối nén tương thích với máy khách MariaSQL
  • người đóng góp

Đóng góp

Muốn cải thiện điều gì đó trong

// get the client
const mysql = require('mysql2');

// create the connection to database
const connection = mysql.createConnection({
  host: 'localhost',
  user: 'root',
  database: 'test'
});

// execute will internally call prepare and query
connection.execute(
  'SELECT * FROM `table` WHERE `name` = ? AND `age` > ?',
  ['Rick C-137', 53],
  function(err, results, fields) {
    console.log(results); // results contains rows returned by server
    console.log(fields); // fields contains extra meta data about results, if available

    // If you execute same statement again, it will be picked from a LRU cache
    // which will save query preparation time and give better performance
  }
);
5. Vui lòng kiểm tra Đóng góp. md để được hướng dẫn chi tiết về cách bắt đầu

Làm cách nào để kết nối với mysql2?

Để kết nối với Máy chủ MySQL. .
Định vị máy khách dòng lệnh MySQL. .
Chạy ứng dụng khách. .
Nhập mật khẩu của bạn. .
Lấy danh sách cơ sở dữ liệu. .
Tạo cơ sở dữ liệu. .
Chọn cơ sở dữ liệu bạn muốn sử dụng. .
Tạo bảng và chèn dữ liệu. .
Kết thúc làm việc với MySQL Command-Line Client

Làm cách nào để sử dụng mysql2 trong nút js?

Dưới đây là cách sử dụng MySQL trong Node theo năm bước đơn giản. .
Tạo một dự án mới. mkdir kiểm tra mysql && cd kiểm tra mysql
Tạo một gói. tập tin json. npm init -y
Cài đặt mô-đun mysql. npm cài đặt mysql
Tạo một ứng dụng. js và sao chép đoạn mã bên dưới (chỉnh sửa trình giữ chỗ cho phù hợp)
Chạy tập tin. ứng dụng nút