nodejsでデータベースを実装するにはどうすればよいですか?

MySQL データベースを使用する例は次のとおりです。対応するデータベースドライバを使用することにより、Node.js でデータベース操作を実行できます。

  1. 最初に、MySQLドライバのインストールを行います。
npm install mysql
  1. Node.js のコードで mysql モジュールを読み込み、データベース接続を作成する:
const mysql = require('mysql');
const connection = mysql.createConnection({
host: 'localhost',
user: 'root',
password: 'password',
database: 'database_name'
});
connection.connect((err) => {
if (err) throw err;
console.log('Connected to MySQL database');
});
  1. データベースクエリを実行する:
connection.query('SELECT * FROM table_name', (err, rows) => {
if (err) throw err;
console.log(rows);
});
  1. データベース接続を閉じる:
connection.end((err) => {
if (err) throw err;
console.log('Disconnected from MySQL database');
});

これは単なる単純な例ですので、挿入、更新、削除などのニーズに合わせて、データベース操作をさらに複雑にすることができます。また、MongoDB の mongoose、PostgreSQL の pg などの他のデータベースドライバを使用することもできます。

bannerAds