简体   繁体   中英

How do I use Node.js to integrate with sql and use in my project

I have created a database using XAMPP and used Node.js to read/write to the table I created in the db. Now i am at a brick wall. I have no idea where to start to get the information retrieved using Node.js into my project.

Also, if I am creating tables and viewing more than just one tables data then I will need to be running these nodes inside my project as the user interacts with the website. I need some insight on how this all wraps together and would like some direction.

I tried opening a new tab that opens localhost:3307 and then get the information from that page to get the table data but this will only work once for my App.js file and it will only do what that file does specifically. What if I need to do more than just read the table data?

You have to use a database driver to interact nodejs with a database. At first you have to install MySql npm package and then config it in this way.

const mysql      = require('mysql');
const connection = mysql.createConnection({
  host     : 'localhost',
  user     : 'root',
  password : 'mypassword',
  database : 'MyDatabase'
});
connection.connect();

then you can make queries on your database using connection object.

connection.query('SELECT * FROM myTable', function (error, results, fields) {
  if (error) throw error;
  console.log('my Result is: ', results);
});

At first you have to install MySql npm package and then config it in this way.

const mysql      = require('mysql');
const conn = mysql.createConnection({
  host     : 'localhost',
  user     : 'root',
  password : 'yourpassword',
  database : 'youtDatabaseName'
});
conn.connect();

Then Query accordingly

connection.query('SELECT * FROM table', function (error, results, fields) {
  if (error) throw error;
  console.log('Result is: ', results);
});

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