connect to database in javascript

To connect to a database in JavaScript, you can use the MySQL library which can be installed with NPM. First, you'll need to create a MySQL connection with the required credentials. This can be done by the following code snippet:

index.tsx
const mysql = require('mysql');

const connection = mysql.createConnection({
  host: 'localhost',
  user: 'username',
  password: 'password',
  database: 'database_name'
});

connection.connect((err) => {
  if (err) {
    console.error('Error connecting: ' + err.stack);
    return;
  }

  console.log('Connected as ID ' + connection.threadId);
});
349 chars
18 lines

Once you've established a connection, you can perform queries using the connection.query() method. For example:

index.tsx
connection.query('SELECT * FROM table_name', (error, results, fields) => {
  if (error) throw error;
  // Do something with the results
});
140 chars
5 lines

To use async-await syntax, you can wrap the query method in a promise and then use async-await. Here's an example:

index.tsx
const query = (sql, args) => {
  return new Promise((resolve, reject) => {
    connection.query(sql, args, (error, results) => {
      if (error) reject(error);
      else resolve(results);
    });
  });
};

(async () => {
  try {
    const results = await query('SELECT * FROM table_name');
    console.log(results);
  } catch (error) {
    console.error(error);
  }
})();
374 chars
18 lines

Note that this is just a basic example of connecting to a database, and you should ensure that you handle errors and sanitize user input to prevent SQL injection attacks.

gistlibby LogSnag