Use Nodejs to connect to mysql to implement basic operations
This article mainly introduces the method of Nodejs connecting to mysql and realizing the operations of adding, deleting, modifying and querying. It combines the example form with a detailed analysis of the connection of nodejs to mysql database, the creation of mysql database and the nodejs adding, deleting, modifying and querying of mysql. For specific implementation skills of related operations, friends in need can refer to
This article describes how Nodejs connects to mysql and implements add, delete, modify, and check operations. Share it with everyone for your reference, the details are as follows:
1. Prepare
nodejs tutorials, most of which use mongodb as an example. However, mongodb has some limitations, which are stated on the official website. I plan to use MySQL because I still have some experience using it. Focus on research first. node-mysql is currently the most popular mysql driver under node. I used it initially, because the asynchronous callback method really has a lot of pitfalls.
The package name of the following project is mysql, and the version is mysql@ 2.5.4
First explain the code shown below, which all starts with the following code, and will not be explained later
var connection = mysql.createConnection({ host : '127.0.0.1', user : 'root', password : 'root123', port: '3306', database: 'my_news_test', });
The meaning of the code is very straightforward. If you want to go deeper, you can go to the official website above to check. Configurations such as host and user should be clear to those who have written MySQL database applications. Please modify the corresponding parameters by yourself. The following code assumes that there is a table called node_use in the database "my_news_test". The table has 3 attributes
id: auto-increment primary key
name: The name has unique restrictions.
age: Age
Test MySQL MySQL version: 5.5
2. Create a database and insert 5 entries Record
Source Database : my_news_test SET FOREIGN_KEY_CHECKS=0; -- ---------------------------- -- Table structure for node_user -- ---------------------------- DROP TABLE IF EXISTS `node_user`; CREATE TABLE `node_user` ( `id` int(11) NOT NULL AUTO_INCREMENT, `name` varchar(30) DEFAULT NULL, `age` int(8) DEFAULT NULL, PRIMARY KEY (`id`) ) ENGINE=InnoDB AUTO_INCREMENT=6 DEFAULT CHARSET=utf8; -- ---------------------------- -- Records of node_user -- ---------------------------- INSERT INTO `node_user` VALUES ('1', 'admin', '32'); INSERT INTO `node_user` VALUES ('2', 'dans88', '45'); INSERT INTO `node_user` VALUES ('3', '张三', '35'); INSERT INTO `node_user` VALUES ('4', 'ABCDEF', '88'); INSERT INTO `node_user` VALUES ('5', '李小二', '65');
3. Test the environment first
1. First you need to install the mysql package of nodejs
D:\User\myappejs4>npm install mysql mysql@2.5.4 node_modules\mysql ├── require-all@0.0.8 ├── bignumber.js@1.4.1 └── readable-stream@1.1.13 (inherits@2.0.1, string_decoder@0.10.31, isarray@0 .0.1, core-util-is@1.0.1)
2. Write code for interaction between nodejs and mysql
//mysql.js //首先需要安装nodejs 的mysql包 //npm install mysql //编写nodejs与mysql交互的代码 var mysql = require('mysql'); var TEST_DATABASE = 'my_news_test'; var TEST_TABLE = 'node_user'; //创建连接 var client = mysql.createConnection({ user: 'root', password: 'root123', }); client.connect(); client.query("use " + TEST_DATABASE); client.query( 'SELECT * FROM '+TEST_TABLE, function selectCb(err, results, fields) { if (err) { throw err; } if(results) { for(var i = 0; i < results.length; i++) { console.log("%d\t%s\t%s", results[i].id, results[i].name, results[i].age); } } client.end(); } );
3. Running results
D:\User\myappejs4>node mysqltest.js 1 admin 32 2 dans88 45 3 张三 35 4 ABCDEF 88 5 李小二 65
4. Node. js combined with MySQL's add, delete, modify, and query operations
1, add
var mysql = require('mysql'); var connection = mysql.createConnection({ host : '127.0.0.1', user : 'root', password : 'root123', port: '3306', database: 'my_news_test', }); connection.connect(); var userAddSql = 'INSERT INTO node_user(id,name,age) VALUES(0,?,?)'; var userAddSql_Params = ['Wilson', 55]; //增 add connection.query(userAddSql,userAddSql_Params,function (err, result) { if(err){ console.log('[INSERT ERROR] - ',err.message); return; } console.log('-------INSERT----------'); //console.log('INSERT ID:',result.insertId); console.log('INSERT ID:',result); console.log('#######################'); }); connection.end();
run as follows
D:\User\myappejs4>node mysqltestadd.js -------INSERT---------- INSERT ID: { fieldCount: 0, affectedRows: 1, insertId: 6, serverStatus: 2, warningCount: 0, message: '', protocol41: true, changedRows: 0 } #######################
2. Change
var mysql = require('mysql'); var connection = mysql.createConnection({ host : '127.0.0.1', user : 'root', password : 'root123', port: '3306', database: 'my_news_test', }); connection.connect(); var userModSql = 'UPDATE node_user SET name = ?,age = ? WHERE id = ?'; var userModSql_Params = ['Hello World',99,7]; //改 up connection.query(userModSql,userModSql_Params,function (err, result) { if(err){ console.log('[UPDATE ERROR] - ',err.message); return; } console.log('----------UPDATE-------------'); console.log('UPDATE affectedRows',result.affectedRows); console.log('******************************'); }); connection.end();
and the running result is as follows
D:\User\myappejs4>node mysqltest_up.js ----------UPDATE------------- UPDATE affectedRows 1 ******************************
3. Check the operation
var mysql = require('mysql'); var connection = mysql.createConnection({ host : '127.0.0.1', user : 'root', password : 'root123', port: '3306', database: 'my_news_test', }); connection.connect(); var userGetSql = 'SELECT * FROM node_user'; //查 query connection.query(userGetSql,function (err, result) { if(err){ console.log('[SELECT ERROR] - ',err.message); return; } console.log('---------------SELECT----------------'); console.log(result); console.log('$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$'); }); connection.end();
and the running result is as follows
D:\User\myappejs4>node mysqltest_query.js ---------------SELECT---------------- [ { id: 1, name: 'admin', age: 32 }, { id: 2, name: 'dans88', age: 45 }, { id: 3, name: '张三', age: 35 }, { id: 4, name: 'ABCDEF', age: 88 }, { id: 5, name: '李小二', age: 65 }, { id: 6, name: 'Wilson', age: 55 } ] $$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$
4. Delete operation
var mysql = require('mysql'); var connection = mysql.createConnection({ host : '127.0.0.1', user : 'root', password : 'root123', port: '3306', database: 'my_news_test', }); connection.connect(); var userDelSql = 'DELETE FROM node_user WHERE id = 7'; //ɾ connection.query(userDelSql,function (err, result) { if(err){ console.log('[DELETE ERROR] - ',err.message); return; } console.log('-------------DELETE--------------'); console.log('DELETE affectedRows',result.affectedRows); console.log('&&&&&&&&&&&&&&&&&'); }); connection.end(); 运行的结果如下 D:\User\myappejs4>node mysqltest_del.js -------------DELETE-------------- DELETE affectedRows 1 &&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&
The above is what I compiled for everyone. I hope it will be helpful to everyone in the future.
Related articles:
How to package static resources in vue
What are the usages of async&await in Koa2?
In the zTree tree plug-in, how to implement click-loading in five-level regions across the country
How to implement node express personalized chat rooms?
The above is the detailed content of Use Nodejs to connect to mysql to implement basic operations. For more information, please follow other related articles on the PHP Chinese website!

The future trends of Python and JavaScript include: 1. Python will consolidate its position in the fields of scientific computing and AI, 2. JavaScript will promote the development of web technology, 3. Cross-platform development will become a hot topic, and 4. Performance optimization will be the focus. Both will continue to expand application scenarios in their respective fields and make more breakthroughs in performance.

Both Python and JavaScript's choices in development environments are important. 1) Python's development environment includes PyCharm, JupyterNotebook and Anaconda, which are suitable for data science and rapid prototyping. 2) The development environment of JavaScript includes Node.js, VSCode and Webpack, which are suitable for front-end and back-end development. Choosing the right tools according to project needs can improve development efficiency and project success rate.

Yes, the engine core of JavaScript is written in C. 1) The C language provides efficient performance and underlying control, which is suitable for the development of JavaScript engine. 2) Taking the V8 engine as an example, its core is written in C, combining the efficiency and object-oriented characteristics of C. 3) The working principle of the JavaScript engine includes parsing, compiling and execution, and the C language plays a key role in these processes.

JavaScript is at the heart of modern websites because it enhances the interactivity and dynamicity of web pages. 1) It allows to change content without refreshing the page, 2) manipulate web pages through DOMAPI, 3) support complex interactive effects such as animation and drag-and-drop, 4) optimize performance and best practices to improve user experience.

C and JavaScript achieve interoperability through WebAssembly. 1) C code is compiled into WebAssembly module and introduced into JavaScript environment to enhance computing power. 2) In game development, C handles physics engines and graphics rendering, and JavaScript is responsible for game logic and user interface.

JavaScript is widely used in websites, mobile applications, desktop applications and server-side programming. 1) In website development, JavaScript operates DOM together with HTML and CSS to achieve dynamic effects and supports frameworks such as jQuery and React. 2) Through ReactNative and Ionic, JavaScript is used to develop cross-platform mobile applications. 3) The Electron framework enables JavaScript to build desktop applications. 4) Node.js allows JavaScript to run on the server side and supports high concurrent requests.

Python is more suitable for data science and automation, while JavaScript is more suitable for front-end and full-stack development. 1. Python performs well in data science and machine learning, using libraries such as NumPy and Pandas for data processing and modeling. 2. Python is concise and efficient in automation and scripting. 3. JavaScript is indispensable in front-end development and is used to build dynamic web pages and single-page applications. 4. JavaScript plays a role in back-end development through Node.js and supports full-stack development.

C and C play a vital role in the JavaScript engine, mainly used to implement interpreters and JIT compilers. 1) C is used to parse JavaScript source code and generate an abstract syntax tree. 2) C is responsible for generating and executing bytecode. 3) C implements the JIT compiler, optimizes and compiles hot-spot code at runtime, and significantly improves the execution efficiency of JavaScript.


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

PhpStorm Mac version
The latest (2018.2.1) professional PHP integrated development tool

mPDF
mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

MinGW - Minimalist GNU for Windows
This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

MantisBT
Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

EditPlus Chinese cracked version
Small size, syntax highlighting, does not support code prompt function
