node.js - 使用 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');
});
解决方案
您似乎正在寻找端口配置:
const db = mysql.createConnection({
host : 'localhost',
user : 'root',
password : '123456',
database: 'nodemysql',
port: 1234
});
检查链接中的连接选项: https ://github.com/mysqljs/mysql
推荐阅读
- java - RecycleView 中的 onBindViewHolder 问题
- javascript - 如何使用 css 更改 .js 中的行
- python - 美丽的汤 - 如何获得
- 来自 div 类的项目和
- 没有任何 ul 的类名和 ID
- 来自 div 类的项目和
- javascript - 为什么我不能同时使用 DOM 和 discord.js?
- php - 从 MySQL 数据库中获取日期时间字段值
- angular - 如何在 Laravel 中通过 Ajax 下载 Excel 文件?
- ibm-cloud - 如果我监控了多个属性,OpenScale 仪表板中的公平值是多少?
- kubernetes - 从主机访问 Minikube 负载均衡器服务
- drools - 如何扩展规则以覆盖现有规则
- mysql - ORDER BY 基于多个 WHERE 案例,这可能吗?