Linux教程網
Linux教程網
Linux教程網
您现在的位置: Linux教程網 >> UnixLinux >  >> Linux綜合 >> Linux資訊 >> 更多Linux

用 C、Java、PHP 操作 PostgreSQL 的三種寫法

PostgreSQL 的成熟度不輸 MySQL,以下示範三種常見工具如何與它互動。

一、C 語言:libpq 基本流程

這支程式在 RedHat 6.0 上驗證通過,示範 create、insert、select、update、drop 這幾個最常用的 SQL。核心觀念是:先設定連線參數(傳 NULL 就採用環境變數的預設值),用 PQsetdb 建立連線,用 PQexec 執行指令,用完結果記得 PQclear 釋放,最後 PQfinish 關閉。

#include <stdio.h>
#include <libpq-fe.h>

int main(void)
{
    char *pghost = NULL, *pgport = NULL;
    char *pgoptions = NULL, *pgtty = NULL;
    char *dbName = "mytest";
    int i, j;
    PGconn *conn;
    PGresult *res;

    conn = PQsetdb(pghost, pgport, pgoptions, pgtty, dbName);
    if (PQstatus(conn) == CONNECTION_BAD) {
        fprintf(stderr, "Connection to database '%s' failed.\n", dbName);
        fprintf(stderr, "%s", PQerrorMessage(conn));
        return 1;
    }

    res = PQexec(conn, "BEGIN");
    if (!res || PQresultStatus(res) != PGRES_COMMAND_OK) {
        fprintf(stderr, "BEGIN command failed\n");
        PQclear(res);
        return 1;
    }
    PQclear(res);

    PQexec(conn, "create table test1 (name char(20), age int4)");
    PQexec(conn, "insert into test1 values ('cjm', 10)");
    PQexec(conn, "insert into test1 values ('eight', 20)");
    PQexec(conn, "insert into test1 values ('Linuxaid', 30)");

    res = PQexec(conn, "select * from test1");
    for (i = 0; i < PQntuples(res); i++) {
        for (j = 0; j < PQnfields(res); j++)
            printf("%-15s", PQgetvalue(res, i, j));
        printf("\n");
    }
    PQclear(res);

    PQexec(conn, "update test1 set age = 25 where name = 'eight'");
    PQexec(conn, "drop table test1");
    PQfinish(conn);
    return 0;
}

二、Java:先搞定 JDBC 驅動與 classpath

從網上下載 PostgreSQL 的 JDBC 驅動,解包後是一個 jar 檔,重點是把它的路徑加進 classpath。我在這裡卡了很久:JDK 1.2 平時不需要 classpath,於是我把 jar 丟到 jdk 目錄、在 makefile 裡指定路徑,怎麼試都是 class not found;建立 classpath 環境變數後才通過。

另外,JDBC 到處要包 try/catch,不然很容易出錯。準備工作:

postmaster -S -i
createuser eight
createdb mytest
psql mytest
mytest=> create table test1 (name char(10), age int4);
mytest=> \q
import java.sql.*;

public class db {
    public static void main(String[] argv) {
        Connection pdb;
        try {
            Class.forName("postgresql.Driver");
        } catch (ClassNotFoundException e) {
            System.out.println("err: class.forName.");
            return;
        }
        try {
            pdb = DriverManager.getConnection(
                      "jdbc:postgresql:mytest", "eight", "");
            Statement stmt = pdb.createStatement();
            ResultSet rs = stmt.executeQuery("select * from test1");
            while (rs != null && rs.next()) {
                System.out.print(rs.getString(1));
                System.out.print(rs.getInt(2));
                System.out.print(" ");
            }
            rs.close();
            stmt.close();
            pdb.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

三、PHP:用 pg_* 函式或 PHPLIB

PHPLIB 操作各類資料庫的方式一致,只要換成對應的 db_pgsql.inc 即可。把 PHPLIB 的 .inc 檔放進 cgi-bin 下的 phplib 目錄,再把該目錄填進 php.ini 的 include_path,每支程式頂端 require("common.php3") 就能拿到 DB_Sql 類別。

直接用原生函式也不麻煩:

<?php
$conn = pg_connect("", "", "", "", "mytest");
if (!$conn) { echo "無法連接資料庫."; exit; }

$rst = pg_exec("select * from test1", $conn);
if (!$rst) { echo "執行 SQL 錯誤!"; exit; }

$fields_num = pg_num_fields($rst);
for ($i = 0; $i < $fields_num; $i++) {
    $fields[$i] = pg_field_name($rst, $i);
    echo "<th>" . $fields[$i] . "</th>";
}

while ($record = pg_fetch_array($rst)) {
    echo "<tr>";
    for ($i = 0; $i < $fields_num; $i++) {
        $value = $record[$fields[$i]];
        echo "<td>" . ($value == "" ? "-" : $value) . "</td>";
    }
    echo "</tr>";
}
pg_free_result($rst);
pg_close($conn);
?>

三種語言的取用邏輯其實一致:建立連線、執行查詢、遍歷結果、釋放資源。差別只在各語言的函式庫風格。

Copyright © Linux教程網 All Rights Reserved