Node.js Synchronous queries with MySQL

前端 未结 6 1992
走了就别回头了
走了就别回头了 2021-01-01 23:23

I\'m working on creating a user registration system for a website that I am working on but I am running into a few issues.

I\'m trying to stay away from having to ne

相关标签:
6条回答
  • 2021-01-01 23:35

    I know I am late to this party but I feel I can help people like me that needed a way to use MySQL in a synchronous way.

    Answer is here.

    Oh and I had to add a pool.end(); after my query code to close the connection and stop the infinite wait loop. See here.

    0 讨论(0)
  • 2021-01-01 23:37

    Symplest solution I could find is the sync-sql module. Install the required modules

    npm install sync-sql
    npm install sync-mysql 
    

    Sample index.js

    const Mysql = require('sync-mysql') 
    
    
    const connection = new Mysql({ 
        host:'localhost', 
        user:'root', 
        password:'password', 
        database:'demo'
    }) 
      
    var result = connection.query('SELECT NOW()') 
    console.log(result) 
    

    https://www.geeksforgeeks.org/how-to-run-synchronous-queries-using-sync-sql-module-in-node-js/

    0 讨论(0)
  • 2021-01-01 23:38

    There could be conditions when you need sync queries (or at least for readability or simplicity). I do not agree with that everything have to be done in the async way at node.js.

    I have tested a lot of available solutions and ended up with the "sync-mysql" module (https://github.com/ForbesLindesay/sync-mysql).

    Easy to install and use, but not that good in performance (especially if you have to do a lot of sub-queries).

    0 讨论(0)
  • 2021-01-01 23:48

    As jfriend00 said above, if you're going to develop in node.js, then you MUST become comfortable with writing async code.

    "chained promises" is probably your best bet:

    • https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/then

    • http://html5hive.org/node-js-quickies-working-with-mysql/

    ADDENDUM:

    This tutorial illustrates promise chaining with node.js SQL queries. It also discusses how you can use Q and/or Step to simplify your code:

    • http://code.tutsplus.com/tutorials/managing-the-asynchronous-nature-of-nodejs--net-36183
    0 讨论(0)
  • 2021-01-01 23:48

    You could simply use a module for node that provide synchronous functions. Here you'll find a module that provide sync/async functions to deal with mysql.

    https://github.com/Will-I4M/node-mysql-libmysqlclient

    Here is how you could use it in order to execute a synchronous query :

    var config = require("./config.json") ;
    var mysql = require('mysql-libmysqlclient') ;
    var client = mysql.createConnectionSync(config.host, config.user, config.password, config.database) ;
    
    var query = "SELECT * FROM Users ;" ;
    var handle = client.querySync(query) ;
    var results = handle.fetchAllSync() ;
    
    console.log(JSON.stringify(results)) ; 
    
    0 讨论(0)
  • 2021-01-01 23:54

    For most things I code in node.js, I like asynchronous code. However, I completely understand that asynchronous code is extremely and dangerously incompatible with the need to write and maintain business logic. I've used a variety of alternative methods. The modules to make things synchronous still leave you with data scoping issues that complicate things. Promises worked best for me. Using that approach, I found myself practically writing an interpreter for a new language on top of JavaScript. I may seem absurd but the most practical and safest method for me ended up being to use the shelljs module and the mysql shell client. It's not great execution performance but it makes for much better developer performance and keeps business logic clear and orderly, as is crucial for business logic. Here's snippet of code to give an example of some of what I created:

    var shell = require('shelljs');
    
    module.exports = {
        user: '',
        password: '',
    
        runSql: function (sql) {
            var command = "echo '" + sql.replace(/'/g, "'\\''") + "' | mysql -u" + this.user.replace(/'/g, "'\\''") + " -p'" + this.password.replace(/'/g, "'\\''") + "'";
            var raw = shell.exec(command, {silent: true}).stdout;
            //console.log( 'BASH -> MySQL YIELD: "' + raw + '"' );
            if (raw.substr(0, 5) === 'ERROR') {
                console.log('ERROR Resulting from: ' + sql + '\n' + raw);
                return [];
            }
            var rows = raw.split('\n');
            var names = [];
            for (var r = 0; r < rows.length; r += 1) {
                columns = rows[r].split('\t');
    
                // Capture column names
                if (r === 0) {
                    names = columns;
                    continue;
                }
    
                // Reformat row into named valued
                var fields = {};
                for (var c = 0; c < columns.length; c += 1) {
                    fields[names[c]] = columns[c];
                }
                rows[r] = fields;
            }
    
            // Eliminate extraneous first and last rows
            rows.splice(0, 1);
            rows.splice(rows.length - 1, 1);
    
            return rows;
        },
    
    }
    
    0 讨论(0)
提交回复
热议问题