可以从Go代码连接到h2数据库http://www.h2database.com吗
发布于 2018-06-11 20:43:31
首先,您需要运行您的DB服务器,允许通过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运行该脚本将生成以下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)现在您的服务器已准备好进行客户端连接,您可以测试是否将web浏览器连接到指定的IP和端口,例如:http://192.168.1.130:8082/login.do
请务必下载Go postgres驱动程序表单"github.com/lib/pq".
现在,您可以从另一个主机(如果需要,也可以是相同的主机)使用以下代码来测试您的连接:
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发布于 2016-01-05 00:59:32
根据http://www.h2database.com/html/advanced.html的说法
...它支持PostgreSQL网络协议...对PostgreSQL网络协议的支持是非常新的,应该看作是实验性的。它不应该用于生产应用程序。
因此,github.com/lib/pq驱动程序很有可能与h2一起工作。
发布于 2020-11-15 01:10:28
我已经为Go开发了一个“本地”Apache H2数据库驱动程序。
https://github.com/jmrobles/h2go
在它的时代,我尝试使用Postgres接口,但我在诊断SQL语法中的bug时遇到了问题。
我想提供一个可以直接访问h2的TCP接口的纯go替代方案。
https://stackoverflow.com/questions/34586722
复制相似问题