简体   繁体   中英

connecting to mysql from ejs file

I am new to node.js and am trying to learn how to connect to mysql database from ejs file. I tried to search for sample code however the code is not working. Can someone please check it out for me. Thank you.

function loaddata() {

          var sql = require("mysql");
          var con = mysql.createConnection({});
          con.connect(function (err) {
              if (err) {
                  console.log('Error connecting to Db');
                  return;
              }
              console.log('Connection established');
          });
          con.query('update students set name="sus" where email="smn14@mail.aub.edu"', function (err, rows) {
              if (err) throw err;

              console.log('Data received from Db:\n');
              console.log(rows);
          });
          con.end(function (err) {
              // The connection is terminated gracefully
              // Ensures all previously enqueued queries are still
              // before sending a COM_QUIT packet to the MySQL server.
          });


      }

The create connect is worst.

 var mysql      = require('mysql'); 
 var connection = mysql.createConnection({   
     host : 'localhost',
     user : 'me', 
     password : 'secret',   
     database : 'my_db' 
 });     
 connection.connect();     
 connection.query('SELECT 1 + 1 AS solution', function(err, rows,
 fields) {   
     if (err) throw err;     
     console.log('The solution is: ', rows[0].solution); });     
 connection.end();

From this example, you can learn the following:

 Every method you invoke on a connection is queued and executed in sequence. Closing the connection is done using end() which makes sure all remaining queries are executed before sending a quit packet to the

mysql server.

Docs

I now understand the process of server/clients. Makes sense, otherwise you would be able to see the database passwords stored in Client.js. :-)

But, there is one way that works for me. The client call a javascript-function and send a message to the server. The server receives this message and starts a database query. Send the result to all clients via socket.io

At the client in the file.ejs

<script type='text/javascript'>

  let socket = io.connect();

  function getSql(userId) {
    socket.emit('start-new-sql-querie',{
        userId: userId
    });
  }

  socket.on('new-sql-result', function (data){ // listen for the new sql result
      console.log(data.userStatus); // foo something with the new data
  })

</script>

<button onclick="getSql(1)">Test sql query</button>

database connection.js at server side

const connection = {
    connectionLimit: 10,
    host: "localhost",
    user: "Abc",
    password: "1234",
    database: "d001",
    multipleStatements: true
};

module.exports = connection;

yourapp.js at server side

const express = require('express'); 
const port = process.env.PORT || 1234;
const app = express();
const server = require('http').createServer(app);
const mysql = require('mysql2');
const config = require('./routes/connection'); // SQL-Connection
const pool = mysql.createPool(config);

let io = require('socket.io')(server);

io.sockets.on('connection', function(socket) {

  socket.on('start-new-sql-querie', function(data) { // listen from the clients

    let user_id = data.userId;
    sql_test.getConnection((error, connection) => { // Connect to sql database
      console.log("user_id: ", user_id)
      connection.query(`SELECT * FROM user WHERE id='${user_id}'`, (err, result) => {
        socket.emit('new-sql-result',{ // send sql result-status to all clients
          userStatus: result.result[0].status
        })
      })
      connection.release();
    })

  });

})

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM