🔥码云GVP开源项目 12k star Uniapp+ElementUI 功能强大 支持多语言、二开方便! 广告
[TOC] ## docker 启动 cockroachdb ``` docker run --name=cr -d -p 26257:26257 -p 9090:9090 cockroachdb/cockroach start --insecure --store=hello-1 --http-addr=:9090 ``` golang ``` package main import ( "database/sql" "fmt" _ "github.com/lib/pq" ) func main() { // 数据库连接字符串 connStr := "postgresql://username:password@localhost:26257/mydb?sslmode=disable" // 打开数据库连接 db, err := sql.Open("postgres", connStr) if err != nil { fmt.Println("Error connecting to the database:", err) return } defer db.Close() // 确认连接是否正常 err = db.Ping() if err != nil { fmt.Println("Error pinging the database:", err) return } fmt.Println("Successfully connected to CockroachDB!") // 创建一个示例表 _, err = db.Exec("CREATE TABLE IF NOT EXISTS users (id SERIAL PRIMARY KEY, name STRING, age INT)") if err != nil { fmt.Println("Error creating table:", err) return } fmt.Println("Table created successfully.") // 插入数据 _, err = db.Exec("INSERT INTO users (name, age) VALUES ($1, $2)", "Alice", 30) if err != nil { fmt.Println("Error inserting data:", err) return } fmt.Println("Data inserted successfully.") // 查询数据 rows, err := db.Query("SELECT id, name, age FROM users") if err != nil { fmt.Println("Error querying data:", err) return } defer rows.Close() fmt.Println("Users:") for rows.Next() { var id int var name string var age int err = rows.Scan(&id, &name, &age) if err != nil { fmt.Println("Error scanning row:", err) return } fmt.Printf("ID: %d, Name: %s, Age: %d\n", id, name, age) } err = rows.Err() if err != nil { fmt.Println("Error iterating over rows:", err) return } } ```