# Node.js/Python/Java 示例

URL: https://caijiao.org/postgresql/project/integration/code-examples
Source: docs/postgresql/project/integration/code-examples.md
Description: 本章节展示了如何在 Node.js、Python 和 Java 中连接 PostgreSQL 数据库，进行基本的数据库操作示例，帮助开发者快速入门。

在开发应用程序时，连接并操作 PostgreSQL 数据库是常见的需求。以下是如何在 Node.js、Python 和 Java 中连接 PostgreSQL 并进行基本数据库操作的示例。

## Node.js 示例

在 Node.js 中，我们可以使用 `pg` 库来连接和操作 PostgreSQL 数据库。以下是一个简单的示例，展示了如何执行查询操作：

### 安装 pg 模块

首先，安装 `pg` 模块：

```bash
npm install pg
````

### 连接 PostgreSQL 数据库

```javascript
const { Client } = require('pg');

// 创建连接配置
const client = new Client({
  user: 'your_user',
  host: 'localhost',
  database: 'your_database',
  password: 'your_password',
  port: 5432,
});

// 连接数据库
client.connect()
  .then(() => {
    console.log('Connected to PostgreSQL');
    
    // 执行查询操作
    return client.query('SELECT NOW()');
  })
  .then(res => {
    console.log('Current Time:', res.rows[0]);
  })
  .catch(err => {
    console.error('Error:', err.stack);
  })
  .finally(() => {
    // 关闭连接
    client.end();
  });
```

## Python 示例

在 Python 中，我们可以使用 `psycopg2` 库来连接 PostgreSQL 数据库。以下是一个简单的示例，展示了如何执行查询操作：

### 安装 psycopg2 模块

首先，安装 `psycopg2` 模块：

```bash
pip install psycopg2
```

### 连接 PostgreSQL 数据库

```python
import psycopg2

# 创建连接
conn = psycopg2.connect(
    dbname='your_database',
    user='your_user',
    password='your_password',
    host='localhost',
    port='5432'
)

# 创建游标
cur = conn.cursor()

# 执行查询
cur.execute('SELECT NOW()')

# 获取查询结果
current_time = cur.fetchone()
print('Current Time:', current_time)

# 关闭游标和连接
cur.close()
conn.close()
```

## Java 示例

在 Java 中，我们可以使用 `JDBC` 来连接 PostgreSQL 数据库。以下是一个简单的示例，展示了如何执行查询操作：

### 导入 PostgreSQL JDBC 驱动

首先，在项目中添加 PostgreSQL JDBC 驱动依赖：

```xml
<!-- 在 pom.xml 中添加依赖 -->
<dependency>
  <groupId>org.postgresql</groupId>
  <artifactId>postgresql</artifactId>
  <version>42.2.5</version>
</dependency>
```

### 连接 PostgreSQL 数据库

```java
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;

public class PostgresExample {
    public static void main(String[] args) {
        try {
            // 连接数据库
            Connection conn = DriverManager.getConnection(
                "jdbc:postgresql://localhost:5432/your_database", 
                "your_user", 
                "your_password"
            );

            // 创建语句
            Statement stmt = conn.createStatement();

            // 执行查询
            ResultSet rs = stmt.executeQuery("SELECT NOW()");

            // 处理结果
            if (rs.next()) {
                System.out.println("Current Time: " + rs.getString(1));
            }

            // 关闭连接
            rs.close();
            stmt.close();
            conn.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
```

## 小结

在本章节中，我们介绍了如何在 Node.js、Python 和 Java 中连接 PostgreSQL 数据库，并执行简单的查询操作。通过这些示例，您可以快速上手在不同语言中使用 PostgreSQL，进行基本的数据库操作。了解如何正确配置和连接数据库是开发应用程序的重要基础，能够帮助您更好地与数据库进行交互。
