How to access a RowDataPacket object

前端 未结 14 2410
悲&欢浪女
悲&欢浪女 2020-11-29 03:02

I\'m currently developing a desktop application with Node-webkit. During that process I need to get some data from a local MySQL-database.

The querying works fine, b

14条回答
  •  情深已故
    2020-11-29 03:07

    If anybody needs to retrive specific RowDataPacket object from multiple queries, here it is.

    Before you start

    Important: Ensure you enable multipleStatements in your mysql connection like so:

    // Connection to MySQL
    var db = mysql.createConnection({
      host:     'localhost',
      user:     'root',
      password: '123',
      database: 'TEST',
      multipleStatements: true
    });
    

    Multiple Queries

    Let's say we have multiple queries running:

      // All Queries are here
      const lastCheckedQuery = `
        -- Query 1
        SELECT * FROM table1
        ;
    
        -- Query 2
        SELECT * FROM table2;
        `
        ;
    
      // Run the query
      db.query(lastCheckedQuery, (error, result) => {
        if(error) {
          // Show error
          return res.status(500).send("Unexpected database error");
        }
    

    If we console.log(result) you'll get such output:

    [
      [
        RowDataPacket {
          id: 1,
          ColumnFromTable1: 'a',
        }
      ],
      [
        RowDataPacket {
          id: 1,
          ColumnFromTable2: 'b',
        }
      ]
    ]
    

    Both results show for both tables.

    Here is where basic Javascript array's come in place https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array

    To get data from table1 and column named ColumnFromTable1 we do

    result[0][0].ColumnFromTable1 // Notice the double [0]
    

    which gives us result of a.

提交回复
热议问题