英文:
How to resolve `invalid packet size, it is shorter than header size` error
问题
我正在尝试连接到我的数据库,但是遇到以下错误:
2022/11/10 13:30:43 invalid packet size, it is shorter than header size
我的代码:
var server = "123.45.67.89"
var port = 3030
var user = "myUserId"
var password = "MyPassword"
var database = "myDB"
func main() {
// 构建连接字符串
connString := fmt.Sprintf("server=%s;user id=%s;password=%s;port=%d;database=%s;",
server, user, password, port, database)
var err error
// 创建连接池
db, err = sql.Open("sqlserver", connString)
if err != nil {
log.Fatal("Error creating connection pool: ", err.Error())
}
ctx := context.Background()
err = db.PingContext(ctx)
if err != nil {
fmt.Println("Catching ERR")
log.Fatal(err.Error())
}
fmt.Printf("Connected!\n")
}
在以下代码行中捕获了一个错误:
err = db.PingContext(ctx)
有人知道如何解决这个问题吗?请帮忙。
英文:
I am trying to connect to my db. but getting the following Error:
2022/11/10 13:30:43 invalid packet size, it is shorter than header size
My Code:
var server = "123.45.67.89"
var port = 3030
var user = "myUserId"
var password = "MyPassword"
var database = "myDB"
func main() {
// Build connection string
connString := fmt.Sprintf("server=%s;user id=%s;password=%s;port=%d;database=%s;",
server, user, password, port, database)
var err error
// Create connection pool
db, err = sql.Open("sqlserver", connString)
if err != nil {
log.Fatal("Error creating connection pool: ", err.Error())
}
ctx := context.Background()
err = db.PingContext(ctx)
if err != nil {
fmt.Println("Catching ERR")
log.Fatal(err.Error())
}
fmt.Printf("Connected!\n")
}
At this following line it is catching an error:
err = db.PingContext(ctx)
Do Someone knows, how I can resolve this issue?
Please help.
答案1
得分: 1
我尝试了另一种连接到数据库的方式,对我来说有效。
package main
import (
"database/sql"
"fmt"
_ "github.com/go-sql-driver/mysql"
)
func main() {
fmt.Println("Golang: My Sql Connection Code:")
db, err := sql.Open("mysql", "userName:password@tcp(123.45.67.89:3030)/myDB")
if err != nil {
panic(err.Error())
}
defer db.Close()
fmt.Println("连接成功")
data, err := db.Query("select * from my_user_table")
if err != nil {
panic(err.Error())
}
}
英文:
I tried another way to connect to DB. and it worked for me.
package main
import (
"database/sql"
"fmt"
_ "github.com/go-sql-driver/mysql"
)
func main() {
fmt.Println("Golang: My Sql Connection Code:")
db, err := sql.Open("mysql", "userName:password@tcp(123.45.67.89:3030)/myDB")
if err != nil {
panic(err.Error())
}
defer db.Close()
fmt.Println("Connection Successful")
data, err := db.Query("select * from my_user_table")
if err != nil {
panic(err.Error())
}
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论