Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- Open Command Line.
- # Initialize npm
- 1. npm init -y
- 2. create run.js file and copy belove code
- 3. node run.js
- --------------------------------------------------------------
- const mysql = require('mysql2');
- const axios = require('axios');
- // Create a connection to the MySQL database
- const connection = mysql.createConnection({
- host: 'localhost',
- user: 'root',
- password: '',
- database: 'practice_db'
- });
- // Function to get the pin code from the Postal API
- async function getPinCodeFromAPI(villageName) {
- try {
- const response = await axios.get(`https://api.postalpincode.in/postoffice/${encodeURIComponent(villageName)}`);
- if (response.data && response.data[0].Status === 'Success') {
- const pinCode = response.data[0].PostOffice[0].Pincode;
- return pinCode; // Return the found pin code
- } else {
- console.log(`No pin code found for village: ${villageName}`);
- return null; // Return null if no pin code found
- }
- } catch (error) {
- console.error('Error fetching pin code from API:', error.message);
- return null; // Return null in case of an error
- }
- }
- // Function to fetch data from the database and update pin codes
- async function updatePinCodes() {
- try {
- // Fetch data from the database
- const [rows] = await connection.promise().query(`
- SELECT s.state_name, d.dist_name, sd.sub_dist_name, v.village_name, v.village_id
- FROM tbl_state AS s
- LEFT JOIN tbl_dist AS d ON s.state_id = d.state_id
- LEFT JOIN tbl_sub_dist AS sd ON sd.dist_id = d.dist_id
- LEFT JOIN tbl_village AS v ON v.sub_dist_id = sd.sub_dist_id
- WHERE s.status = 'active'
- `);
- // Iterate over each village and get the pin code
- for (const row of rows) {
- const villageName = row.village_name;
- console.log(`Checking pin code for village: ${villageName}`);
- // Fetch the pin code from the API
- const pinCode = await getPinCodeFromAPI(villageName);
- if (pinCode)
- {
- // If a pin code is found, update the database
- console.log(`Updating pin code for ${villageName} to ${pinCode}`);
- // Update the pin code in the tbl_village table
- await connection.promise().query(
- 'UPDATE tbl_village SET pin_code = ? WHERE village_id = ?',
- [pinCode, row.village_id]
- );
- }
- }
- console.log('Pin code update process completed!');
- } catch (err) {
- console.error('Error:', err.message);
- } finally {
- // Close the connection
- connection.end();
- }
- }
- // Run the update process
- updatePinCodes();
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement