Node.js select a MySQL database

To select a MySQL database and insert data into a table within that database using Node.js, you need to modify the previous code by specifying the database in the connection and using the selected database in the SQL query. Here's an example:

const mysql = require('mysql');

// Create a connection to the database
const connection = mysql.createConnection({
  host: 'localhost', // Replace with your host name
  user: 'yourusername', // Replace with your database username
  password: 'yourpassword', // Replace with your database password
  database: 'yourdatabase', // Replace with your database name
});

// Connect to the database
connection.connect((err) => {
  if (err) {
    console.error('Error connecting to the database: ' + err.stack);
    return;
  }
  console.log('Connected to the database as id ' + connection.threadId);

  // Select the database
  connection.query('USE yourdatabase', (error) => {
    if (error) throw error;
    console.log('Database selected successfully');

    // Perform the insert query
    const data = { name: 'John Doe', email: 'johndoe@example.com' };
    connection.query('INSERT INTO your_table SET ?', data, (err, results) => {
      if (err) throw err;
      console.log('Inserted a new row with ID:', results.insertId);

      // Close the connection
      connection.end((err) => {
        if (err) {
          console.error('Error closing the database connection: ' + err.stack);
          return;
        }
        console.log('Connection closed.');
      });
    });
  });
});

Make sure to replace the placeholder values for host, user, password, yourdatabase, and your_table with your MySQL database connection details and the specific database and table you want to work with.

In this example, we first use the USE statement to select the database and then perform the insert query. Adjust the data object and the SQL query according to your specific table structure and data.

Komentar

Postingan populer dari blog ini

WhatsApp Web login QR code in an HTML page using whatsapp-web.js

Node.js Telegram Bot API send an image with text

Add these security headers to your website