Server/개발

[Node.js] mysql 연동

sangjun-pro 2022. 5. 19. 10:44

1. mysql 설치

[root@localhost server1]# npm install -S mysql
npm notice created a lockfile as package-lock.json. You should commit this file.
npm WARN server1@1.0.0 No repository field.

+ mysql@2.18.1
added 11 packages from 15 contributors and audited 11 packages in 1.804s
found 0 vulnerabilities



   ╭────────────────────────────────────────────────────────────────╮
   │                                                                │
   │      New major version of npm available! 6.14.16 → 8.10.0      │
   │   Changelog: https://github.com/npm/cli/releases/tag/v8.10.0   │
   │               Run npm install -g npm to update!                │
   │                                                                │
   ╰────────────────────────────────────────────────────────────────╯

 

2. DB 관련 내용 작성

var mysql = require("mysql");
var pool = mysql.createPool({
	connectionLimit: "10",
	host: "localhost", // IP or URL
	port: "3306", // DB port
	user: "user",
	password: "password",
	database: "schemasname",
	debug: false
});

3. API 작성 및 호출

 

//API
var sensor_device =
{
    get_data: function(idata, callback)
    {
        mysql.getConnection(function(err,conn)
        {
            if(err)
            {
                console.log("ERR : " + err);
                if(conn) conn.release();
                callback(err, null);
                return;
            }
            conn.query("select * from value where number=?",idata,
            function(err,result)
            {
                conn.release();
                if(err)
                {
                    console.log("QUERY ERR"+ err);
                    callback(err, null);
                    return;
                }
                else
                {
                    var string = JSON.stringify(result[0]);
                    var json = JSON.parse(string);
                    var DeviceInfo = json;
                    callback(null, DeviceInfo);
                }
            });
        });
    }
}

// Call Function
	Sensor_device.get_data(datano,function(err, DeviceInfo){
		if (err) return;
		if(info) console.log(param.param1);
	});

 

'Server > 개발' 카테고리의 다른 글

[ VSCode ] Thunder Client - API 테스트 툴  (0) 2022.05.19
[Node.js] console.log time stamp  (0) 2022.05.19
[ VSCode] Centos7 서버 원격 개발  (0) 2022.04.27
[Node.js] mysql 연동 issue  (0) 2022.04.25
[Node.js] HEX array parsing  (0) 2022.04.14