package database
import (
"database/sql"
"fmt"
"log"
_ "github.com/lib/pq" // add this
)
type FuckTheDatabaseClass struct {
Postgres_sql *sql.DB
}
type TestUser struct {
Email string
Username *string
Head_image *string //base64 string of an image
Sex *int32 //AI detect. 0: female, 1: male
Age *int32 //AI detect.
}
func (self FuckTheDatabaseClass) Init() error {
postgres_sql_information := fmt.Sprintf(
"host=%s port=%d user=%s password=%s dbname=%s sslmode=disable",
"127.0.0.1", 5432,
"yingshaoxo", "yingshaoxo",
"postgres")
db, err := sql.Open("postgres", postgres_sql_information)
if err != nil {
log.Fatal(err)
}
self.Postgres_sql = db
//*self.Postgres_sql = *db
return err
}
func (self FuckTheDatabaseClass) Print_all_data_in_a_table(table_name string) error {
user := TestUser{}
err := self.Postgres_sql.QueryRow("SELECT 'yingshaoxo', NULL").Scan(&user.Username, &user.Age)
// error in here
log.Println(user.Username)
log.Println(user.Age)
return err
}
When I call Print_all_data_in_a_table("user"), an error happen.
Error message is:
Exception has occurred: panic
"runtime error: invalid memory address or nil pointer dereference"
Stack:
2 0x00000001004efe14 in testing.tRunner.func1.2
at /opt/homebrew/Cellar/go/1.19.3/libexec/src/testing/testing.go:1396
3 0x00000001004ef710 in testing.tRunner.func1
at /opt/homebrew/Cellar/go/1.19.3/libexec/src/testing/testing.go:1399
7 0x0000000100554b8c in database/sql.(*DB).conn
at /opt/homebrew/Cellar/go/1.19.3/libexec/src/database/sql/sql.go:1288
8 0x0000000100556174 in database/sql.(*DB).query
at /opt/homebrew/Cellar/go/1.19.3/libexec/src/database/sql/sql.go:1730
(truncated)
My questions are:
why the db variable sql.Open() returns are not copyable? If it is copyable, I could simply use it anywhere.
If you guys already implemented the whole PostgreSQL driver logic, why don't you guys make a new package to simplify the SQL development process? I mean, like what I did, to make the sql as an inner variable inside of a struct(class).
Here is the code 1:
When I call
Print_all_data_in_a_table("user")
, an error happen.Error message is:
My questions are:
db
variablesql.Open()
returns are not copyable? If it is copyable, I could simply use it anywhere.sql
as an inner variable inside of a struct(class).