Postman 本身无法直接连接数据库,需通过后端 API 或中间件间接操作。以下是在 Ubuntu 下通过不同方式连接数据库的步骤:
安装依赖
sudo apt update
sudo apt install nodejs npm
npm install -g xmysql
启动 xMySQL 服务
xmysql -h localhost -u root -p your_password -d your_database -r 3000
-h
:数据库主机(Ubuntu 本地为 localhost
)-p
:数据库密码-r
:指定服务端口(如 3000
)在 Postman 中操作
GET
请求到 http://localhost:3000/api/表名
POST
请求到 http://localhost:3000/api/表名
,Body 选择 raw
→ JSON
,输入数据。开发后端服务
使用 Express.js 连接 MySQL,示例代码:
const express = require('express');
const mysql = require('mysql');
const app = express();
const connection = mysql.createConnection({
host: 'localhost',
user: 'root',
password: 'your_password',
database: 'your_database'
});
connection.connect();
app.get('/users', (req, res) => {
connection.query('SELECT * FROM users', (err, results) => {
res.json(results);
});
});
app.listen(3000, () => console.log('Server running on port 3000'));
在 Postman 中测试
GET
请求,URL 输入 http://localhost:3000/users
,发送即可获取数据。安装 PostgREST
sudo apt install postgrest
配置数据库连接
编辑配置文件(如 /etc/postgrest.conf
):
db-uri = "postgresql://username:password@localhost:5432/your_database"
db-schema = "public"
server-port = 3000
启动服务并测试
sudo service postgrest start
在 Postman 中发送 GET
/POST
等请求到 http://localhost:3000/表名
。
开发后端服务
使用 Spring Boot 或 Express 连接 PostgreSQL,示例(Spring Boot):
# application.properties
spring.datasource.url=jdbc:postgresql://localhost:5432/your_database
spring.datasource.username=your_username
spring.datasource.password=your_password
在 Postman 中测试
通过 GET
/POST
等请求调用后端 API,如 http://localhost:8080/api/users
。
-r
或 server-port
调整。通过以上方法,可在 Ubuntu 下通过 Postman 间接操作数据库,满足 API 测试或数据验证需求。