[英]Create table in db with mysql2
I have a question, I want to create a function for auto create table in my database.我有一个问题,我想为我的数据库中的自动创建表创建一个 function。
I have my models 'MpModel.js':我有我的模型“MpModel.js”:
//import connection
import db from "../config/database.js";
export const insertMpTab = (id, result) => {
db.query(
"CREATE TABLE IF NOT EXISTS `mp_"+id+"` (`mpLine_date` date DEFAULT NULL, `mpLine_id` int NOT NULL AUTO_INCREMENT, PRIMARY KEY (`mpLine_id`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci;",
[id],
(err, results) => {
if (err) {
console.log(err);
result(err, null);
} else {
result(null, results);
}
}
);
};
and controllers 'mp.js':和控制器“mp.js”:
import {
insertMpTab,
} from "../models/MpModel.js";
// Create new mp
export const createMpTab = (req, res) => {
insertMpTab(req.params.id, (err, results) => {
if (err) {
res.send(err);
} else {
res.json(results);
}
});
};
and routes.js:和路线.js:
//import express
import express from "express";
import {
createMpTab,
} from "../controllers/mp.js";
//init express router
const router = express.Router();
router.post("/mp/:id/", createMpTab)
//export default router
export default router;
I think my problem comes from my code.我认为我的问题来自我的代码。 If you know or have an idea, even the docs that explains it because I haven't found it.如果您知道或有想法,即使是解释它的文档也是如此,因为我还没有找到它。
Thankyou谢谢
Passing [id]
to your query looks redundant, right now.现在将[id]
传递给您的查询看起来是多余的。
Note: If id
comes from user input, it opens up the possibility for SQL injection.注意:如果id
来自用户输入,它会打开 SQL 注入的可能性。 To overcome this, validate the variable, and reject any non-valid input.要克服这个问题,请验证变量并拒绝任何无效输入。
const tableName = `mp_${id}`;
const query = "CREATE TABLE IF NOT EXISTS `" + tableName + "` (`mpLine_date` date DEFAULT NULL, `mpLine_id` int NOT NULL AUTO_INCREMENT, PRIMARY KEY (`mpLine_id`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci"
export const insertMpTab = (id, result) => {
db.query(
query,
(err, results) => {
if (err) {
console.log(err);
result(err, null);
} else {
result(null, results);
}
}
);
};
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.