Advertisement
djbob2000

sql connect

Apr 24th, 2024
65
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. import Koa from 'koa';
  2. import { Pool } from 'pg';
  3. import fs from 'fs';
  4.  
  5. const app = new Koa();
  6. const port = process.env.PORT || 3000;
  7.  
  8. const pool = new Pool({
  9.   user: 'your_postgres_user',
  10.   host: 'your_postgres_host',
  11.   database: 'your_postgres_database',
  12.   password: 'your_postgres_password',
  13.   port: 5432, // Default PostgreSQL port
  14. });
  15.  
  16. const createTables = async () => {
  17.   const client = await pool.connect();
  18.  
  19.   try {
  20.     // Read the SQL queries from the file
  21.     const sqlQueries = fs.readFileSync('edulab.sql', 'utf8');
  22.  
  23.     // Split the SQL queries into an array
  24.     const queries = sqlQueries.split(/;\s*$/m);
  25.  
  26.     // Execute each query
  27.     for (const query of queries) {
  28.       if (query.trim().length > 0) {
  29.         await client.query(query);
  30.       }
  31.     }
  32.  
  33.     console.log('Tables created successfully');
  34.   } catch (err) {
  35.     console.error('Error creating tables:', err);
  36.   } finally {
  37.     client.release();
  38.   }
  39. };
  40.  
  41. app.listen(port, async () => {
  42.   console.log(`Server running on http://localhost:${port}`);
  43.  
  44.   try {
  45.     await createTables();
  46.   } catch (err) {
  47.     console.error('Error creating tables:', err);
  48.   }
  49. });
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement