const mysql = require("mysql2");
const tools = require("../tools");
const sql_help ={}
const status = false;
const connection = mysql.createConnection(tools.getTaskDataBaseConfig());


sql_help.isHaveBook=function(book_id,call_back){
  connection.query('SELECT * FROM video_product where product_id = '+book_id, (error, results, fields) => {
    if (error) {
      console.log('The isHaveBook no find!');
      call_back(false)
    }else{
      if(results.length<=0){
        call_back(false,results) 
      }else{
        call_back(true) //这本书还没
      }
    }
  });
}

sql_help.update = function(sql,updateValues,call_back){
  connection.query(sql, updateValues, (error, results, fields) => {
    if (error) {
      console.error('更新数据失败: ' + error.stack);
      return;
    }
    if(call_back!=null){
      call_back()
    }
  });
}
// const info = { name: 'John Doe', email: 'johndoe@example.com' };
// const sql = 'INSERT INTO users SET ?';
sql_help.query = function(sql,info,call_back){

    connection.query(sql, info, (error, results, fields) => {
      if (error) {
        console.log("query error:",error)
        // console.log("error info :",sql+info)
      }else{
        call_back(results,fields)
      }
    });
  
}

sql_help.get = function(sql,call_back){
  connection.query(sql, (error, results, fields) => {
    if (error) {
      console.log("query error:",error)
      call_back(false,null)
    }else{
      call_back(true,results) //找到了
    }
  });
}

sql_help.find = function(sql,call_back){
  connection.query(sql, (error, results, fields) => {
    if (error) {
      console.log('The no find!',sql,error);
      call_back(false)
    }else{
      if(results.length<=0){
        call_back(false,results) 
      }else{
        call_back(true,results) //找到了
      }
    }
  });
}

sql_help.connect = function(call_back){
  connection.connect(err => {
    if (err) {
      console.error('Error connecting to the database:', err.stack);
      call_back(false)
      return;
    }
    call_back(true)
    console.log('Connected to the MySQL server.');
  });
}

module.exports = sql_help;