我应该如何从 HTML 表单向 MYSQL 数据库插入数据?
How should I insert data to MYSQL database from a HTML form?
我知道节点在后端运行,虽然通过 server.js 文件连接到 SQL 数据库不是问题,但我无法理解如何从 js 中做到这一点链接到一个表单元素(那绝对是客户端 js,我无法从那里建立连接)。我知道这可能令人困惑,所以我非常感谢任何帮助。
我是初学者,所以请保持简单。 Youtube 视频也不错。提前致谢:)
const mysql = require("mysql");
//create connection to sql database
const connection = mysql.createConnection({
host: "localhost",
user: "root",
password: "",
database: "blog",
});
connection.query('select * from posts', () => {
console.log('done');
})
//this works when i put it inside server.js (using express) but not inside some other file- says cannot use require.
简单明了,这就是数据库连接的初始化。为了在其他文件中使用此连接对象,您需要将其导出或将其合并到 express 支持的“req”对象中。我建议在文件末尾添加
module.exports ={
connection : mysql.createConnection(config)
}
然后使用连接对象在其他地方进行查询。
除此之外,我建议您开始使用 Sequelize,因为它是 nodejs 的强大 ORM。首先学习 sql 逻辑并通过 Mysql workbench 、 pgadmin 等直接在数据库中测试您的查询,然后深入研究 sequelize 文档,让自己更上一层楼。希望这个回答能解决您的问题!
我知道节点在后端运行,虽然通过 server.js 文件连接到 SQL 数据库不是问题,但我无法理解如何从 js 中做到这一点链接到一个表单元素(那绝对是客户端 js,我无法从那里建立连接)。我知道这可能令人困惑,所以我非常感谢任何帮助。 我是初学者,所以请保持简单。 Youtube 视频也不错。提前致谢:)
const mysql = require("mysql");
//create connection to sql database
const connection = mysql.createConnection({
host: "localhost",
user: "root",
password: "",
database: "blog",
});
connection.query('select * from posts', () => {
console.log('done');
})
//this works when i put it inside server.js (using express) but not inside some other file- says cannot use require.
简单明了,这就是数据库连接的初始化。为了在其他文件中使用此连接对象,您需要将其导出或将其合并到 express 支持的“req”对象中。我建议在文件末尾添加
module.exports ={
connection : mysql.createConnection(config)
}
然后使用连接对象在其他地方进行查询。 除此之外,我建议您开始使用 Sequelize,因为它是 nodejs 的强大 ORM。首先学习 sql 逻辑并通过 Mysql workbench 、 pgadmin 等直接在数据库中测试您的查询,然后深入研究 sequelize 文档,让自己更上一层楼。希望这个回答能解决您的问题!