You can execute MySQL queries from your Node.js application. For example, MySQL uses following statement to create simple table in database
Example SQL Query:-
1 | CREATE TABLE users (user_id INT(100), user_name VARCHAR(255), email VARCHAR(255)) |
Now try to create the same table through a Node.js application. Let’s create a create_mysql_table.js file
vim create_mysql_table.js
Add the following content. Update the MySQL details according to your setup. Also, make sure that database already exists on MySQL server.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 | var mysql = require('mysql'); var dbconn = mysql.createConnection({ host: "localhost", port: "3306", user: "root", password: "secret", database: "tecadmin" }); dbconn.connect(function(err) { if (err) throw err; console.log("Database connected successfully!"); var sqlquery = "CREATE TABLE users (user_id INT(100), user_name VARCHAR(255), email VARCHAR(255))"; dbconn.query(sqlquery, function (err, result) { if (err) throw err; console.log("Table created successfully"); }); }); |
Execute the file using node command. If everything goes fine, you will see results like below.
node create_mysql_table.js Output: Database connected successfully! Table created successfully