Computer >> 컴퓨터 >  >> 프로그램 작성 >> MySQL

NodeJS를 사용하여 MySQL에서 레코드 업데이트

<시간/>

이 기사에서는 NodeJS를 사용하여 MySQL에서 레코드를 업데이트하는 방법을 살펴보겠습니다. Node.js 서버에서 MySQL 테이블 값을 동적으로 업데이트합니다. 업데이트 후 select 문을 사용하여 MySql 레코드가 업데이트되었는지 확인할 수 있습니다.

계속하기 전에 다음 단계가 이미 실행되었는지 확인하십시오 -

  • mkdir mysql-test

  • cd mysql-test

  • npm 초기화 -y

  • npm 설치 mysql

위의 단계는 프로젝트 폴더에 Node - mysql 종속성을 설치하기 위한 단계입니다.

학생 테이블에 레코드 업데이트 −

  • 기존 레코드를 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 }