如何使用javascript调用存储过程?

问题描述 投票:0回答:1

服务器.js :

const express = require('express');
const mysql = require('mysql2');
const path = require('path');
const app = express();

app.use(express.json());

const db = mysql.createConnection({
  host: 'localhost',
  user: 'root',
  password: 'password',
  database: 'db_name',
});

// Connect to MySQL
db.connect((err) => {
  if (err) {
    console.error('Error connecting to the database:', err);
    return;
  }
  console.log('Connected to MySQL database');
});

// Serve static files (HTML, CSS, JS) from the 'public' folder
app.use(express.static('public'));

// Serve index.html at root
app.get('/', (req, res) => {
  res.sendFile(path.join(__dirname, 'public/index.html'));
});

// Serve home.html at /home
app.get('/home', (req, res) => {
  res.sendFile(path.join(__dirname, 'public/home.html'));
});

// Serve about.html at /about
app.get('/about', (req, res) => {
  res.sendFile(path.join(__dirname, 'public/about.html'));
});


app.get('/get-data', (req, res) => {
  db.query('SELECT * FROM Weather_Stations', (err, results) => {
    if (err) {
      res.status(500).send('Error fetching data from Weather_Stations');
      return;
    }
    res.json(results);
  });
});
// API endpoint to get station_id values from Weather_Stations for Weather_Data table
app.get('/get-station-ids', (req, res) => {
  db.query('SELECT station_id FROM Weather_Stations', (err, results) => {
    if (err) {
      console.error('Error fetching station IDs:', err);
      res.status(500).send('Error fetching station IDs');
      return;
    }
    res.json(results);
  });
});

// API endpoint to get data from Weather_Data
app.get('/get-weather-data', (req, res) => {
  db.query('SELECT * FROM Weather_Data', (err, results) => {
    if (err) {
      console.error('Error fetching Weather_Data:', err);
      res.status(500).send('Error fetching Weather_Data');
      return;
    }
    res.json(results);
  });
});
// --------------------------------- Genarate Weather ID --------------------------------------------
app.get('/generate-weatherData-id', async (req, res) => {
  try {
    const [result] = await db.query("CALL region_id_gen(?)", ['WD']);
    const generatedId = result[0]?.NextNumber || null; // Extract the ID from the result
    if (generatedId) {
      res.status(200).json({ weatherData_id: `WD-${generatedId}` });
    } else {
      res.status(500).json({ error: 'Failed to generate weatherData_id' });
    }
  } catch (error) {
    console.error("Error generating weatherData_id:", error);
    res.status(500).json({ error: 'Internal server error' });
  }
});

// --------------------------------- Start the Server --------------------------------------------
app.use((req, res, next) => {
  console.log(`Request URL: ${req.url}`);
  next();
});

const PORT = 3000;
app.listen(PORT, () => {
  console.log(`Server is running on port ${PORT}`);
});

错误:

服务器正在端口 3000 上运行 已连接MySQL数据库

您尝试对不是 Promise 的查询结果调用 .then()、.catch() 或调用 wait,这是一个编程错误。尝试调用 con.promise().query() 或 require('mysql2/promise') 而不是 'mysql2' 以获得与 Promise 兼容的查询接口版本。要了解如何使用 async/await 或 Promises,请查看 https://sidorares.github.io/node-mysql2/docs#using-promise-wrapper 上的文档,或 https://sidorares 上的 mysql2 文档。 github.io/node-mysql2/docs/documentation/promise-wrapper

生成weatherData_id时出错:错误:您尝试对不是promise的查询结果调用.then()、.catch()或调用await,这是一个编程错误。尝试调用 con.promise().query() 或 require('mysql2/promise') 而不是 'mysql2' 以获得与 Promise 兼容的查询接口版本。要了解如何使用 async/await 或 Promises,请查看 https://sidorares.github.io/node-mysql2/docs#using-promise-wrapper 上的文档,或 https://sidorares 上的 mysql2 文档。 github.io/node-mysql2/docs/documentation/promise-wrapper

at Query.then (C:\Users\Pramudith Rangana\Documents\JavaScript Projects\mySqlDataShow\node_modules\mysql2\lib\commands\query.js:43:11)
at process.processTicksAndRejections (node:internal/process/task_queues:95:5)
javascript mysql node.js
1个回答
0
投票

您在 Node.js 应用程序中尝试使用 mysql2 库调用存储过程时似乎遇到了错误。要解决此问题,您需要确保使用基于 Promise 的 MySQL 连接版本。

以下是如何修改代码以使用 Promise 接口正确调用存储过程:

const express = require('express');  
const mysql = require('mysql2/promise'); // Change here  
const path = require('path');  
const app = express();  

app.use(express.json());  

const db = mysql.createPool({  
  host: 'localhost',  
  user: 'root',  
  password: 'password',  
  database: 'db_name',  
});  

// Serve static files (HTML, CSS, JS) from the 'public' folder  
app.use(express.static('public'));  

// Serve index.html at root  
app.get('/', (req, res) => {  
  res.sendFile(path.join(__dirname, 'public/index.html'));  
});  

// Serve home.html at /home  
app.get('/home', (req, res) => {  
  res.sendFile(path.join(__dirname, 'public/home.html'));  
});  

// Serve about.html at /about  
app.get('/about', (req, res) => {  
  res.sendFile(path.join(__dirname, 'public/about.html'));  
});  

app.get('/get-data', async (req, res) => {  
  try {  
    const [results] = await db.query('SELECT * FROM Weather_Stations');  
    res.json(results);  
  } catch (err) {  
    res.status(500).send('Error fetching data from Weather_Stations');  
  }  
});  

app.get('/get-station-ids', async (req, res) => {  
  try {  
    const [results] = await db.query('SELECT station_id FROM Weather_Stations');  
    res.json(results);  
  } catch (err) {  
    console.error('Error fetching station IDs:', err);  
    res.status(500).send('Error fetching station IDs');  
  }  
});  

app.get('/get-weather-data', async (req, res) => {  
  try {  
    const [results] = await db.query('SELECT * FROM Weather_Data');  
    res.json(results);  
  } catch (err) {  
    console.error('Error fetching Weather_Data:', err);  
    res.status(500).send('Error fetching Weather_Data');  
  }  
});  

// Generate Weather ID  
app.get('/generate-weatherData-id', async (req, res) => {  
  try {  
    const [result] = await db.query("CALL region_id_gen(?)", ['WD']);  
    const generatedId = result[0]?.NextNumber || null; // Extract the ID from the result  
    if (generatedId) {  
      res.status(200).json({ weatherData_id: `WD-${generatedId}` });  
    } else {  
      res.status(500).json({ error: 'Failed to generate weatherData_id' });  
    }  
  } catch (error) {  
    console.error("Error generating weatherData_id:", error);  
    res.status(500).json({ error: 'Internal server error' });  
  }  
});  

// Logging middleware  
app.use((req, res, next) => {  
  console.log(`Request URL: ${req.url}`);  
  next();  
});  

const PORT = 3000;  
app.listen(PORT, () => {  
  console.log(`Server is running on port ${PORT}`);  
});

更改了 MySQL 导入:您现在使用 require('mysql2/promise') 来获取 Promise 兼容版本。 使用createPool而不是createConnection:这对于处理多个连接更有效。 将您的查询方法转换为异步/等待:这与基于承诺的功能相匹配。

© www.soinside.com 2019 - 2024. All rights reserved.