doujiyan0971 2017-09-26 06:09
浏览 41

向数据库发送数据时出错

I'm trying to transfer data to write them to the database. But I have the error "panic: runtime error: invalid memory address or nil pointer dereference" In this function, I wait for the data from the client

func handlePacket(conn net.Conn) {
    rw := bufio.NewReadWriter(bufio.NewReader(conn), bufio.NewWriter(conn))
    defer conn.Close()

    packet := model.RegistrationMessage{}
    client := JsonDecoderMessage(rw).Decode(&packet)
    if client != nil {
        puts("Error from Decode.Please NO :(")
    }

    if packet.MessageType == model.AUTH_MESSAGE {
        puts("Auth")
    } else if packet.MessageType == model.REGS_MESSAGE {
        puts("Regs")
        Registration(packet.Login, packet.Password)
        puts("good")
    }
}

And here I establish connection with a DB and I try to send the data in a DB

var db *sql.DB

func InitDataBase() {
    psqlInfo := fmt.Sprintf("host=%s port=%d user=%s "+
        "password=%s dbname=%s sslmode=disable",
        host, port, user, password, 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!")
}
func Registration(email, password string) {
    sqlStatement := `INSERT INTO account0( email,password)
        VALUES ($1, $2) RETURNING id`
    id := 0
    err := db.QueryRow(sqlStatement, email, password).Scan(&id)
    if err != nil {
        panic(err)
    }
}
  • 写回答

2条回答 默认 最新

  • duanruoyu6675 2017-09-26 06:27
    关注

    defer db.Close() will be executed when InitDataBase() returns, so when you use db in Registration, it causes an error.

    You should call db.Close() just before your program exits, or after you are finished working with the database, whichever comes first.

    评论

报告相同问题?

悬赏问题

  • ¥15 孟德尔随机化结果不一致
  • ¥15 apm2.8飞控罗盘bad health,加速度计校准失败
  • ¥15 求解O-S方程的特征值问题给出边界层布拉休斯平行流的中性曲线
  • ¥15 谁有desed数据集呀
  • ¥20 手写数字识别运行c仿真时,程序报错错误代码sim211-100
  • ¥15 关于#hadoop#的问题
  • ¥15 (标签-Python|关键词-socket)
  • ¥15 keil里为什么main.c定义的函数在it.c调用不了
  • ¥50 切换TabTip键盘的输入法
  • ¥15 可否在不同线程中调用封装数据库操作的类