Connect to MySQL database
First of all, connecting to the MySQL database requires the mysql module.
You can use the npm package manager for installation:
npm install mysql
After the installation is complete, introduce the mysql module:
const mysql = require('mysql');
Next, the database connection can be created using the () method.
This method requires passing in some connection parameters, such as host name, user name, password, database name, etc.:
const connection = ({ host : 'localhost', user : 'root', password : 'password', database : 'mydatabase' });
Among them, host represents the host name of the database, user represents the user name of the database, password represents the password of the database, and database represents the name of the database to be connected.
After the connection is successful, you can use the () method to execute SQL statements to perform database operations.
Implement MySQL database operation interface
The Express framework can be used to implement the MySQL database operation interface.
The following is a query operation as an example to demonstrate how to implement the MySQL database operation interface in a back-end server.
First, create a GET route in the Express application:
('/users', function (req, res) { ('SELECT * FROM users', function (error, results, fields) { if (error) throw error; (results); }); });
This route can be used to query all data in the users table.
In the routing handler, use the () method to execute SQL statements and return the query result to the front end through the () method.
Using MySQL database operation interface in front-end
Using the MySQL database operation interface in the front-end can use the Axios library to send HTTP requests.
Axios is a Promise-based HTTP client that can be used to send HTTP requests of GET, POST and other types.
Here is an example of using the Axios library to send GET requests:
('/users') .then(function (response) { (); }) .catch(function (error) { (error); });
In this example, a GET request was sent using the Axios library, and the requested URL is /users, and the returned result is obtained.
Similarly, the Axios library may be used to send POST requests, PUT requests, DELETE requests, etc.
Summarize
The above is how to use the mysql module in the backend server to connect to the MySQL database and how to implement the MySQL database operation interface.
Using the MySQL database operation interface in the front-end can use the Axios library to send HTTP requests to obtain the data returned by the back-end server.
This allows front-end applications to interact with the back-end database, achieving more flexible and efficient data operations.
These are just personal experience. I hope you can give me a reference and I hope you can support me more.