NodeJSを使用してMySQLのレコードを更新する
この記事では、NodeJSを使用してMySQLのレコードを更新する方法を説明します。 Node.jsサーバーからMySQLテーブルの値を動的に更新します。更新後にselectステートメントを使用して、MySqlレコードが更新されているかどうかを確認できます。
先に進む前に、次の手順がすでに実行されていることを確認してください-
-
mkdir mysql-test
-
cd mysql-test
-
npm init -y
-
npm install mysql
上記の手順は、プロジェクトフォルダにNode-mysqldependecyをインストールするためのものです。
レコードを生徒のテーブルに追加する-
-
既存のレコードをMySQLテーブルに更新するには、最初にapp.jsファイルを作成します
-
次に、以下のスニペットをコピーしてファイルに貼り付けます
-
次のコマンドを使用してコードを実行します
>> node app.js
例
// Checking the MySQL dependency in NPM
var mysql = require('mysql');
// Creating a mysql connection
var con = mysql.createConnection({
host: "localhost",
user: "yourusername",
password: "yourpassword",
database: "mydb"
});
con.connect(function(err) {
if (err) throw err;
var sql = "UPDATE student SET address = 'Bangalore' WHERE name = 'John';"
con.query(sql, function (err, result) {
if (err) throw err;
console.log(result.affectedRows + " Record(s) updated.");
console.log(result);
});
}); 出力
1 Record(s) updated.
OkPacket {
fieldCount: 0,
affectedRows: 1, // This will return the number of rows updated.
insertId: 0,
serverStatus: 34,
warningCount: 0,
message: '(Rows matched: 1 Changed: 1 Warnings: 0', // This will return the
number of rows matched.
protocol41: true,
changedRows: 1 }> 例
// Checking the MySQL dependency in NPM
var mysql = require('mysql');
// Creating a mysql connection
var con = mysql.createConnection({
host: "localhost",
user: "yourusername",
password: "yourpassword",
database: "mydb"
});
con.connect(function(err) {
if (err) throw err;
// Updating the fields with address while checking the address
var sql = "UPDATE student SET address = 'Bangalore' WHERE address = 'Delhi';"
con.query(sql, function (err, result) {
if (err) throw err;
console.log(result.affectedRows + " Record(s) updated.");
console.log(result);
});
}); 出力
3 Record(s) updated.
OkPacket {
fieldCount: 0,
affectedRows: 3, // This will return the number of rows updated.
insertId: 0,
serverStatus: 34,
warningCount: 0,
message: '(Rows matched: 3 Changed: 3 Warnings: 0', // This will return the number of rows matched.
protocol41: true,
changedRows: 3 }> -
Nodejsを使用したMySQLのレコードの削除
挿入後、レコードも削除する必要があります。レコードは、データベーステーブルの識別子に基づいて削除できます。 「DELETEFROM」ステートメントを使用して、テーブルからレコードを削除できます。 MySqlDBからレコードを削除するには2つの方法があります- 静的削除 -このタイプの削除では、削除するプレフィックス付きのフィルター値を指定します 動的削除 –このタイプの削除では、削除する前に入力を求めてから、それに基づいて削除します。 先に進む前に、次の手順がすでに実行されていることを確認してください- mkdir mysql-test cd mysql-te
-
Sequelizeを使用してNodeJSでMySQLテーブルを作成する
続編の紹介 Sequealizeは、Postgres、MySQL、MariaDB、SQLite、MicrosoftSQLServerなどのさまざまなサーバーのpromiseベースのNode.jsORMに従います。 以下は、NodeJSの続編の主な機能の一部です- トランザクションサポート 関係 熱心で遅延読み込み レプリケーションなどを読む... Sequelizeを使用したMySQLへの接続 Sequelizeを使用してMySQLとNode.jsの間の接続を確立する必要があります。 sequelizeとの接続を成功させた後、構成のために次の3つのフ