Slog1_如何使用nodejs与mysql进行数据交互

in 编程
关注公众号【好便宜】( ID:haopianyi222 ),领红包啦~
阿里云,国内最大的云服务商,注册就送数千元优惠券:https://t.cn/AiQe5A0g
腾讯云,良心云,价格优惠: https://t.cn/AieHwwKl
搬瓦工,CN2 GIA 优质线路,搭梯子、海外建站推荐: https://t.cn/AieHwfX9

关注微信公众号“环游的球”

没有人能阻挡我前进的道路

安装nodejs作为开发服务器的工具(macOS)

cd Desktop
mkdir nodejs_learningload
cd nodejs_learningload
/usr/bin/ruby -e "$(curl -fsSL https://raw.githubusercontent...)"
brew install node
node -v

v10.6.0

npm -v

6.1.0

安装Mysql,配置Mysql

brew install mysql
mysql.server start
mysqladmin -u root password 88888888
mysql -u root -p
mysql>
mysql> show databases;
Database
information_schema
mysql
performance_schema
sys

4 rows in set(0.01 sec)

mysql> create database my_db;

Query OK, 1 row affected (0.02 sec)

mysql> use my_db;

Database changed

mysql> CREATE TABLE Account
(
ID int NOT NULL AUTO_INCREMENT,
AccountName varchar(255) NOT NULL,
Password varchar(255) NOT NULL,
PRIMARY KEY (ID)
);

Query OK, 0 rows affected (0.09 sec)

mysql> INSERT INTO Account (AccountName, Password)
VALUES ('ArthurSlog','ArthurSlog);

Query OK, 1 row affected (0.08 sec)

mysql> SELECT * FROM Account;

ID|AccountName|Password

1 | KingArthur | KingArthur
1 row in set (0.00 sec)

exit;

Bye

实现nodejs和Mysql的数据交互

cd ~/Desktop/nodejs_learningload
npm init
sudo npm install express

index.html

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>SingUp</title>
</head>
<body>
    <p>Sing up</p>
    <form action="http://127.0.0.1:8081/singupAccount" method="GET">
        Name: <input type="text" name="name"> 
        <br>
        Password: <input type="text" name="password">
        <br>
        <input type="submit" value="注册">
    </form>
    <br>
</body>
</html>
    <form action="http://127.0.0.1:8081/singupAccount" method="GET">
        Name: <input type="text" name="name"> 
        <br>
        Password: <input type="text" name="password">
        <br>
        <input type="submit" value="注册">
    </form>
action="http://127.0.0.1:8081/singupAccount" method="GET"
action="http://127.0.0.1:8081/singupAccount"
/singupAccount

index.js

var express = require('express');
var fs = require("fs");
var app = express();
 
app.use(express.static(__dirname));

app.get('/singupAccount', function (req, res) {
 
    var mysql      = require('mysql');
    var connection = mysql.createConnection({
      host     : 'localhost',
      user     : 'root',
      password : '88888888',
      database : 'my_db'
    });
     
    connection.connect();

    var response = {
        "name":req.query.name,
        "password":req.query.password
    };

    var  addSql = 'INSERT INTO Account(AccountName, Password) VALUES(?,?)';
    var  addSqlParams = [response.name, response.password];

    connection.query(addSql,addSqlParams,function (err, result) {
        if(err){
            console.log('[INSERT ERROR] - ',err.message);
            res.send('执行sql出错!');
            return;
        }
        res.send('Welcome~ SingUp Success ^_^');
    });

    connection.end();
 })

var server = app.listen(8081, function () {
 
  var host = server.address().address
  var port = server.address().port
 
  console.log("应用实例,访问地址为 http://%s:%s", host, port)
})
var express = require('express');

var app = express();
 
app.use(express.static(__dirname));
var server = app.listen(8081, function () {
 
  var host = server.address().address
  var port = server.address().port
 
  console.log("应用实例,访问地址为 http://%s:%s", host, port)
}
app.get('/singupAccount', function (req, res) {
 
    var mysql      = require('mysql');
    var connection = mysql.createConnection({
      host     : 'localhost',
      user     : 'root',
      password : '88888888',
      database : 'my_db'
    });
     
    connection.connect();

    var response = {
        "name":req.query.name,
        "password":req.query.password
    };

    var  addSql = 'INSERT INTO Account(AccountName, Password) VALUES(?,?)';
    var  addSqlParams = [response.name, response.password];

    connection.query(addSql,addSqlParams,function (err, result) {
        if(err){
            console.log('[INSERT ERROR] - ',err.message);
            res.send('执行sql出错!');
            return;
        }
        res.send('Welcome~ SingUp Success ^_^');
    });

    connection.end();
 })
    var mysql      = require('mysql');
    var connection = mysql.createConnection({
      host     : 'localhost',
      user     : 'root',
      password : '88888888',
      database : 'my_db'
    });
connection.connect();
req.query.name
req.query.password
    var response = {
        "name":req.query.name,
        "password":req.query.password
    };
    var  addSql = 'INSERT INTO Account(AccountName, Password) VALUES(?,?)';
    var  addSqlParams = [response.name, response.password];

    connection.query(addSql,addSqlParams,function (err, result) {
        if(err){
            console.log('[INSERT ERROR] - ',err.message);
            res.send('执行sql出错!');
            return;
        }
        res.send('Welcome~ SingUp Success ^_^');
    });
connection.end();

最终测试

mysql -u root -p
Enter password:

mysql>
mysql> use my_db;
Database changed
mysql> select * from Account;

ID    AccountName    Password
1    KingArthur    KingArthur
1 row in set (0.00 sec)
mysql> 
node index.js
ID    AccountName    Password
1    KingArthur    KingArthur
2   KingArthur2 KingArthur2
2 row in set (0.00 sec)

欢迎关注我的微信公众号 ArthurSlog

ArthurSlog

如果你喜欢我的文章 欢迎点赞 留言

谢谢

关注公众号【好便宜】( ID:haopianyi222 ),领红包啦~
阿里云,国内最大的云服务商,注册就送数千元优惠券:https://t.cn/AiQe5A0g
腾讯云,良心云,价格优惠: https://t.cn/AieHwwKl
搬瓦工,CN2 GIA 优质线路,搭梯子、海外建站推荐: https://t.cn/AieHwfX9
扫一扫关注公众号添加购物返利助手,领红包
Comments are closed.

推荐使用阿里云服务器

超多优惠券

服务器最低一折,一年不到100!

朕已阅去看看