去H2数据库。

huangapple go评论88阅读模式
英文:

Go to h2 database

问题

可以通过Go代码连接到H2数据库吗?http://www.h2database.com

英文:

Is it possible to connect from Go code to h2 database http://www.h2database.com

答案1

得分: 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

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

# ./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)

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

请确保从"github.com/lib/pq"下载Go的PostgreSQL驱动程序。

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

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)
	}
}

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

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
英文:

First of all you need to run your DB server allowing connections from any host via TCP, PotgreSQL or Web (I have done this by using a linux shell script called runH2Server.sh):

#!/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

Running the script will produce following otuput:

# ./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)

Now your server is ready for client connections, you could test it connecting your web browser to the IP and port specified, for example: http://192.168.1.130:8082/login.do

Be sure to download the Go postgres driver form "github.com/lib/pq".

Now, from another host (or the same if you want) you can use the following code to test your connection:

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 it and you will have the following output:

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

答案2

得分: 2

根据http://www.h2database.com/html/advanced.html的说明:

...它支持PostgreSQL网络协议...对于PostgreSQL网络协议的支持是相当新的,应该被视为实验性的。不应该在生产应用中使用。

因此,github.com/lib/pq驱动程序很有可能与h2数据库兼容。

英文:

According to http://www.h2database.com/html/advanced.html:

> ... it supports the PostgreSQL network protocol ... Support for the PostgreSQL network protocol is quite new and should be viewed as experimental. It should not be used for production applications.

So there is high chance that github.com/lib/pq driver will work with h2.

答案3

得分: 1

我为Go开发了一个“本地”的Apache H2数据库驱动程序。

https://github.com/jmrobles/h2go

在当时,我尝试使用Postgres接口,但在诊断SQL语法错误时遇到了问题。

我希望提供一个纯Go的替代方案,可以直接访问H2的TCP接口。

英文:

I have developed a "native" Apache H2 Database driver for Go.

https://github.com/jmrobles/h2go

In its day I tried to use the Postgres interface but I encountered problems diagnosing bugs in the SQL syntax.

I wanted to provide a pure go alternative that would directly access H2's TCP interface.

huangapple
  • 本文由 发表于 2016年1月4日 15:47:09
  • 转载请务必保留本文链接:https://go.coder-hub.com/34586722.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定