Я делаю проект по системе автоматической генерации таблицы времени. Я новичок в node .js. Это программа для вставки таблицы значений из html в mysql. Когда я запускаю эту программу, это приводит к тупиковой ситуации.
Это мой индексный файл .js.
var express=require('express');
var app=express();
app.set('view engine','ejs');
app.use(express.static('./public'));
app.use(express.static("."));
var Array=require('node-array');
var mysql = require('mysql');
var s=require('string');
//Connection pool
var pool=mysql.createPool({
connectionLimit:10,
host: "localhost",
user: "root",
password: "user@1235",
database:"time_table"
});
app.post('/expt2',urlencodedParser,function(req,res){
var table=req.body.table1;
console.info(req.body);
var data=[];
for(var key in (req.body)){
data.push(req.body[key]);
}
for(i=0;i<(data.length-1);i++)
console.info(data[i]);
var i=0;
while(i<(data.length-1))
{
lg=data[i];
console.info(lg.substr(2,1));
if (lg.substr(2,1)= = "4")
{
sem=4 ;
room = "lh1";
}
else if (lg.substr(2,1)= = "6")
{
sem=6;
room = "lh2";
}
else if (lg.substr(2,1)= = "8")
{
sem=8;
room = "lh3";
}
else
{
sem=5;
room = "lh2";
}
day = "Thrusday";
console.info(room);
console.info(sem);
pool.getConnection(function(err,con){
if (err) throw err;
console.info("Connected!");
console.info(lg);
pool.query("select fid from course where
cid='"+lg+"'",function(err,result)
{
if (err)throw err;
else
{
console.info("okay");
console.info(result);
Object.keys(result).forEach(function(key){
row=result[key];
console.info(row.fid);
ob=row.fid;
console.info(ob);
var sql = "INSERT INTO classroom(sem,day,timings,fid,cid,room_name)
VALUES('"+sem+"','"+day+"','12:00:00','"+ob+"','"+cid+"','"+room+
"');"
con.query(sql,function(err,result)
{
if (err)throw err;
console.info("one row inserted");
//con.release();
});
});
}
});
});
i++;}
});
Это файл expt2.html.
<html>
<head>
<title>Master-Timetable</title>
<link rel = "stylesheet"
href = "/public/asset/css/bootstrap.min.css" type = "text/css"/>
<script type = "text/javascript" src = "/public/asset/popper.min.js">
</script>
<script src = "/public/asset/js/bootstrap.min.js"
type = "text/javascript"></script>
<script src = "/public/asset/jquery-3.2.1.min.js"
type = "text/javascript"></script>
</head>
<body>
<form id = "contacth" method = "POST" action = "/expt2"></form>
<table id = "table1">
<tr class = "head">
<th>Time->day|</th>
<th>7:30-8:30</th>
<th>8:30-9:30</th>
<th>9:30-10:30</th>
<th rowspan = "19">BREAK</th>
<th>11:00-12:00</th>
<th>12:00-1:00</th>
<th rowspan = "19">LUNCH BREAK</th>
<th>2:30-3:30</th>
<th>3:30-4:30</th>
<th>4:30-5:30</th>
</tr>
<tr>
<th rowspan = "3" class = "parent" value = "monday">Monday</th>
<td class = "child"><input type = "text" maxlength = "5" name = "am1"
form = "contacth"></td>
<td ><input type = "text" maxlength = "5" name = "am2" form = "contacth"/>
</td>
<td><input type = "text" maxlength = "5" name = "am3" form = "contacth"/>
</td>
<td><input type = "text" maxlength = "5" name = "am4" form = "contacth"/>
</td>
<td><input type = "text" maxlength = "5" name = "am5" form = "contacth"/>
</td>
<td><input type = "text" maxlength = "5" name = "am6" form = "contacth"/>
</td>
<td><input type = "text" maxlength = "5" name = "am7" form = "contacth"/>
</td>
<td><input type = "text" maxlength = "5" name = "am8" form = "contacth"/>
</td>
</tr>
<tr>
<td>
<input type = "submit" name = "t_save" value = "save" class = "btn btn-
success" form = "contacth"/><br/>
</td>
</tr>
</table>
</body>
</html>
Мне предложили использовать "async" и "await". Но я не совсем понимаю, где использовать "async" и ждать в моем коде.
Старайтесь не запрашивать пул напрямую. Замените первый pool.query на con.query.
См. Этот вопрос: Разница между использованием getConnection () и использованием пула непосредственно в node.js с модулем node-mysql?
Ошибка: ER_TRUNCATED_WRONG_VALUE_FOR_FIELD: Неверное целочисленное значение: ',,,,,,,, 102' для столбца 'fid' в строке 1 в Query.Sequence._packetToError (C: \ sh \ node_modules \ mysql \ lib \ protocol \ sequence \ Sequence .js: 52: 14) в Query.ErrorPacket (C: \ sh \ node_modules \ mysql \ lib \ protocol \ последовательностей \ Query.js: 77: 18) в Protocol._parsePacket (C: \ sh \ node_modules \ mysql \ lib \ протокол \ Protocol.js: 279: 23)
Попробуйте удалить двойные кавычки с обеих сторон + ob +
Похоже, что переменная ob является строкой, а fid ожидает целое число. Убедитесь, что вы передаете соответствующие типы данных и значения для заданных столбцов.
Ob - целочисленная переменная.
Новая ошибка - ER_LOCK_DEADLOCK: обнаружена тупиковая ситуация при попытке получить блокировку; попробуйте перезапустить транзакцию в Query. sequence._packetToError
Что, если вы раскомментируете con.release ()
Никакого эффекта. Это снова приводит к той же проблеме (тупик)
вы можете поместить свою бизнес-логику в функцию, сделав ее модульной, и вы можете использовать async await, или вы можете использовать обещание для обработки асинхронных потоков. Используйте метод pool.getConnection () и получите соединение, а затем запросите с помощью соединения, а затем закройте связь