Node.js is a JavaScript runtime based on the Chrome V8 engine, which allows JavaScript to run on the server side. Node.js is a very popular back-end development language and has been widely used in web applications, mobile applications, desktop applications and other fields. MySQL is a popular relational database that is widely used in various applications and websites. Node.js can easily interact with the MySQL database.
Below we will learn how to use Node.js to write code to connect to the MySQL database for data operations.
Before using Node.js to operate the MySQL database, you need to install the relevant packages:
npm install mysql
Connecting to the database is to operate the database The first step, here is an example of connecting to the MySQL database:
const mysql = require('mysql'); const connection = mysql.createConnection({ host: 'localhost', user: 'root', password: 'password', database: 'test' }); connection.connect(function(err) { if (err) { console.error('error connecting: ' + err.stack); return; } console.log('connected as id ' + connection.threadId); });
In the code, we use the mysql.createConnection()
method to create the MySQL connection object and pass the parameters Give host
, user
, password
, and database
to specify the hostname, username, password, and database name for the connection.
Next, call the connect method of the object to connect to the database. If the connection is successful, a message will be output to the console.
After connecting to the MySQL database, we can execute various SQL statements for data operations. The following is an example of querying data:
connection.query('SELECT * FROM books', function (error, results, fields) { if (error) throw error; console.log('The books are: ', results); });
In the code , we used the connection.query()
method to execute a SQL query statement. SELECT * FROM books
Query all data in the books table. If the query is successful, an array containing the query results will be output on the console. The results include the row's content and metadata (field names, types, etc.).
Inserting data using MySQL in Node.js is similar to querying data. Here is the sample code:
connection.query('INSERT INTO books SET ?', {name: 'Node.js Book', author: 'Tom'}, function (error, results, fields) { if (error) throw error; console.log('The book is inserted:', results.insertId); });
In the code, we use the INSERT INTO
statement to insert a new record into the books table. We use an object to represent the inserted data, the key name corresponds to the column name in the table, and the key value represents the column value.
Similarly, if the insertion is successful, a message will be output on the console.
Updating data in MySQL requires the use of the UPDATE
statement. The code example for updating data using Node.js is as follows:
connection.query('UPDATE books SET author = ? WHERE id = ?', ['Jerry', 123], function (error, results, fields) { if (error) throw error; console.log('The book is updated:', results.affectedRows); });
In the code , we used the UPDATE
statement to update the author of the book record with id 123 to Jerry.
Similarly, if the update is successful, a message will be output on the console.
To delete data in MySQL, you need to use the DELETE
statement. The code example of using Node.js to delete data is as follows:
connection.query('DELETE FROM books WHERE id = ?', [123], function (error, results, fields) { if (error) throw error; console.log('The book is deleted:', results.affectedRows); });
In the code , we used the DELETE FROM
statement to delete the book record with id 123.
Similarly, if the deletion is successful, a message will be output on the console.
Finally, you need to disconnect from the MySQL database:
connection.end();
Through the above examples, we can see , it is very easy to use Node.js to connect to the MySQL database and perform various operations. You only need to install the corresponding dependency packages and then write the corresponding code.
Of course, in actual development, handling error messages is also a very important issue. In the code, we use the sentence if (error) throw error;
to handle error messages, which is not the best approach. A better approach would be to use a try-catch structure to catch exceptions and handle them accordingly.
In short, you can easily build various web applications, mobile applications, desktop applications and other projects using Node.js and MySQL, making development work more efficient, simple and interesting.
The above is the detailed content of How to insert mysql into nodejs. For more information, please follow other related articles on the PHP Chinese website!