首页 > 解决方案 > 使用 Node.js 将 SQL 查询连接到网站?

问题描述

这对我来说是一个全新的领域,所以请放轻松:) 我目前有一个通过 Javascript 编码的网站和一个用于网站接收数据的 SQL 程序。从我目前所做的研究来看,我可以使用快速数据框来做到这一点。我一直在尝试使用 Node.js,目前,我有一些连接到本地主机端口的东西,我使用 sql 创建了一个表和一个插入机制到该表(我将在下面包含我的代码) . 但我不知道如何将 mySQLWorkbench 中的 SQL 查询连接到端口。谁能指出我正确的方向?任何帮助是极大的赞赏!

// including both express and mysql
const express = require('express');
const mysql = require('mysql');

//creat a database connection
const db = mysql.createConnection({
    host : 'localhost',
    user : 'root',
    password : '123456',
    database: 'nodemysql'
});

//connect
db.connect((err) => {
    console.log('MySql connected...');
});

//creaing a simple express server
const app = express();


// creating a database (rout)
app.get('/createdb', (req, res) => { //request and response object
    let sql = 'CREATE DATABASE nodemysql'; 
    // running the query
    db.query(sql, (err, result) => {
        if(err) console.log('ERROR');
        console.log(result)
        res.send('Database created...');
    })
});

// create table
app.get('/createtable', (req,res) => {
    let sql = 'CREATE TABLE posts(id int AUTO_INCREMENT, title VARCHAR(255), body VARCHAR(255), PRIMARY KEY (id))';
    db.query(sql, (err, result) => {
        if(err) console.log('ERROR');
        console.log(result);
        res.send('Appointment table created..');
    })
});

// insert appt 1
app.get('/addappt1', (req, res) => {
    let appt = {title: 'appointment 1', body: 'Appointment 1 at 10 am'};
    let sql = 'INSERT INTO appts SET ?'; // ? is a place hold to what we put as the second parameter
    let query = db.query(sql, appt, (err, result) => {
        if(err) console.log('ERROR');
        console.log(result);
        res.send('Appointment 1 was added')
    });
});

// listening on port 3000
app.listen('3000', () => {
    console.log('Server started on port 3000');
});

标签: node.js

解决方案


您似乎正在寻找端口配置:

const db = mysql.createConnection({
    host : 'localhost',
    user : 'root',
    password : '123456',
    database: 'nodemysql',
    port: 1234
});

检查链接中的连接选项: https ://github.com/mysqljs/mysql


推荐阅读