docker 安装postgres,nodejs连接pg

docker 安装postgres,nodejs连接pg

docker pull Postgres

docker image ls

docker pull dpage/pgadmin4

docker volume create postgres-volume

docker run -d -p 5432:5432 ---name postresql -v Postgres-volume:/var/lib/portgresql/data -e POSTGRES_PASSWORD=portgresPW postgres

docker run -d -p 5433:80 ---name pgadmin4 -e PGADMIN_DEFAULT_EMAIL=test@qq.com -e PGADMIN_DEFAULT_PASSWORD=123456 dpage/pgadmin4

数据库管理后台访问pgadmin4:

http://localhost:5433

用户名:test@qq.com

密码:123456

连接数据库

主机名:host.docker.internal(默认)

用户名:portgres(默认)

密码:portgresPW

pnpm install pg config

config/default.json

json 复制代码
{
  "db":{
      "user": "postgres",
      "host": "127.0.0.1",
      "database": "postgres",
      "password": "pass123",
      "port": "5432"
  }
}

index.js

js 复制代码
import pg from "pg"
import config from "config"
const { Client } = pg
const dbConfig = config.db
const pgClient = new Client(dbConfig)
//1.连接到数据库
pgClient.connect((connectErr) => {
  if (connectErr) {
    console.error(connectErr,"连接失败")
    return
  }
  console.log("连接成功")
//2.执行查询
pgClient.query('SELECT * from tbl_user where username = $1', ['testuser'], (queryErr, res) => {
    if (!queryErr) {
      console.log(res.rows[0])
    } else {
      console.error(queryErr,"查询失败")
    }
//3.关闭连接
    pgClient.end((endErr) => {
      if (endErr) {
        console.error(err,"关闭连接失败")
      }else{
        console.log("关闭连接")
      }
    })
  })
})

package.json

json 复制代码
{
	"name": "postgres-demo",
	"version": "1.0.0",
	"description": "",
	"main": "./src/index.js",
	"author": "hjj",
	"license": "ISC",
	"type": "module",
	"scripts": {
		"dev": "node ./src/index.js"
	},
	"dependencies": {
		"config": "^3.3.12",
		"pg": "^8.12.0"
	}
}
相关推荐
编程大师哥1 小时前
Linux 命名管道(FIFO)通信 超清晰讲解
linux·运维·服务器
Smile_2542204181 小时前
linux服务器清理磁盘
linux·运维·服务器
KivenMitnick1 小时前
Claude Code--Ubuntu Linux超详细配置教程(附每步的可能报错及解决方法)
linux·运维·ubuntu
JoyCong19982 小时前
OpenClaw实践玩法,简单三步搭建自动化工作流(附真香平替方案)
运维·人工智能·自动化
panamera122 小时前
linux下SPI、IIC、UART、CAN的编码
linux·运维·服务器
yj_xqj2 小时前
openGauss 数据库报错“failed: To0 many open files”
运维·数据库
小五传输2 小时前
汽车供应商协同平台如何重塑主机厂与供应商的数字化纽带?
大数据·运维·安全
returnthem3 小时前
虚拟机sda紧急处理扩容(used100%,无空间剩余,开不了机)
linux·运维·服务器
API快乐传递者3 小时前
1688商品数据接口:供应链ERP数字化的核心引擎
java·大数据·运维