转到h2数据库

Kax*_*axa 4 sql h2 go

是否可以从 Go 代码连接到 h2 数据库http://www.h2database.com

小智 5

首先,您需要运行您的数据库服务器,允许通过 TCP、PotgreSQL 或 Web 连接来自任何主机(我使用名为runH2Server.sh的 linux shell 脚本来完成此操作):

#!/bin/bash

export PATH=$PATH:/tmp/H2DB/jre1.8/bin

export CLASSPATH=/tmp/H2DB/DBServer:/tmp/H2DB/DBServer/h2.jar

java -classpath $CLASSPATH org.h2.tools.Server -webAllowOthers -tcpAllowOthers -pgAllowOthers -baseDir /tmp/H2DB/DBServer
Run Code Online (Sandbox Code Playgroud)

运行脚本将产生以下输出:

# ./runH2Server.sh
Web Console server running at http://127.0.1.1:8082 (others can connect)
TCP server running at tcp://127.0.1.1:9092 (others can connect)
PG server running at pg://127.0.1.1:5435 (others can connect)
Run Code Online (Sandbox Code Playgroud)

现在您的服务器已准备好进行客户端连接,您可以测试它是否将 Web 浏览器连接到指定的 IP 和端口,例如:http : //192.168.1.130 : 8082/login.do

请务必从“ github.com/lib/pq ”下载 Go postgres 驱动程序。

现在,从另一台主机(或相同的主机,如果您愿意),您可以使用以下代码来测试您的连接:

package main

import (
    "database/sql"
    "fmt"
    _ "github.com/lib/pq"
)

const (
  host     = "192.168.1.130"
    port = 5435
    user     = "sa"
    password = ""
    dbname   = "/tmp/H2DB/DBServer/test"
)

func main() {
    psqlInfo := fmt.Sprintf("host=%s port=%d user=%s "+
        "dbname=%s sslmode=disable", host, port, user, dbname)

    db, err := sql.Open("postgres", psqlInfo)
    if err != nil {
        panic(err)
    }
    defer db.Close()

    err = db.Ping()
    if err != nil {
        panic(err)
    }
    fmt.Println("Successfully connected!")

    rows, err := db.Query("SHOW TABLES")
    if err != nil {
        panic(err)
    }

    fmt.Println("\n\n=== Tables in DB ===")

    fmt.Printf("%10v | %15v\n", "tablename", "tableschema")
    for rows.Next() {
        var tablename string
        var tableschema string
        err = rows.Scan(&tablename, &tableschema)
        if err != nil {
            panic(err)
        }
        fmt.Printf("%10v | %15v\n", tablename, tableschema)
    }

    fmt.Println("\n\n=== Records in DB ===")

    rows, err = db.Query("SELECT * FROM TEST ORDER BY ID")
    if err != nil {
        panic(err)
    }

    fmt.Printf("%10v | %15v\n", "ID", "NAME")
    for rows.Next() {
        var id int
        var name string
        err = rows.Scan(&id, &name)
        if err != nil {
            panic(err)
        }
        fmt.Printf("%10v | %15v\n", id, name)
    }
}
Run Code Online (Sandbox Code Playgroud)

运行它,您将获得以下输出:

C:\Go\PG_Client
? go run PgDBClient.go
Successfully connected!


=== Tables in DB ===
 tablename |     tableschema
      TEST |          PUBLIC


=== Records in DB ===
        ID |            NAME
         1 |           Hello
         2 |           World
Run Code Online (Sandbox Code Playgroud)