数据无法保存在我的数据库中

时间:2016-05-14 08:27:24

标签: go

我有我的网站,它可以写一些东西。然后我的服务可以获取这些数据并保存在我的数据库中,但它不适合我。我尝试了一些步骤,似乎可以将字符串传输到dab(),但它无法在我的数据库中保存任何内容。

错误日志:

2016/05/14 08:02:08 http: panic serving 14.146.246.141:64540: sql: converting argument #0's type: unsupported type 
[]string, a slice
goroutine 5 [running]:
net/http.(*conn).serve.func1(0xc8200b4f20, 0x7f8b9f86c6c8, 0xc820024038)
    /usr/lib/golang/src/net/http/server.go:1287 +0xb5
main.checkErr(0x7f8b9f867028, 0xc82000b4a0)
    /home/Mario/a.go:50 +0x4b
main.dab(0xc82000b360, 0x1, 0x1, 0xc82000b370, 0x1, 0x1)
    /home/Mario/a.go:41 +0x306
main.handle(0x7f8b9f86c848, 0xc8200b5550, 0xc8200de2a0)
    /home/Mario/a.go:28 +0x4a7
net/http.HandlerFunc.ServeHTTP(0x876a90, 0x7f8b9f86c848, 0xc8200b5550, 0xc8200de2a0)
    /usr/lib/golang/src/net/http/server.go:1422 +0x3a
net/http.(*ServeMux).ServeHTTP(0xc820012930, 0x7f8b9f86c848, 0xc8200b5550, 0xc8200de2a0)
    /usr/lib/golang/src/net/http/server.go:1699 +0x17d
net/http.serverHandler.ServeHTTP(0xc820016120, 0x7f8b9f86c848, 0xc8200b5550, 0xc8200de2a0)
    /usr/lib/golang/src/net/http/server.go:1862 +0x19e
net/http.(*conn).serve(0xc8200b4f20)
    /usr/lib/golang/src/net/http/server.go:1361 +0xbee
created by net/http.(*Server).Serve
    /usr/lib/golang/src/net/http/server.go:1910 +0x3f6

代码段:

package main

import (
    "net/http"
    "log"
    "fmt"
    "html/template"
    _ "github.com/go-sql-driver/mysql"
    "database/sql"
)

func Mai(w http.ResponseWriter, r *http.Request){
        t, _ := template.ParseFiles("a.js")
        t.Execute(w, nil)
}

func FormServer(w http.ResponseWriter, r *http.Request){
        t, _ := template.ParseFiles("an.html")
        t.Execute(w, nil)
}

func handle(w http.ResponseWriter, r *http.Request){
        r.ParseForm()
        fmt.Println("title:", r.Form["title"])
        fmt.Println("main:", r.Form["main"])
        a := r.Form["title"]
        b := r.Form["main"]
        dab(a , b)
        // t, _ := template.ParseFiles("finish.html")
        // t.Execute(w, nil)
}

func dab(a , b []string){
    db, err := sql.Open("mysql", "root:123456@/xiaoyou?charset=utf8")
    checkErr(err)
    stmt, err := db.Prepare("INSERT talk SET title=?,main=?")
    checkErr(err)
    res, err := stmt.Exec(a , b)
    checkErr(err)
    id, err := res.LastInsertId()
    checkErr(err)
    fmt.Println(id)
    db.Close()
}

func checkErr(err error) {
    if err != nil {
        panic(err)
    }
}

func main() {
    http.HandleFunc("/",Mai)
    http.HandleFunc("/login", FormServer)
    http.HandleFunc("/submit",handle)
    err := http.ListenAndServe(":80", nil)
    if err != nil {
        log.Fatal("ListenAndServe:",err)
    }
}

我该如何解决?

1 个答案:

答案 0 :(得分:0)

您正在将一段字符串传递给无法处理它的内容。尝试使用title提取mainr.Form.Get,然后将其传递给您准备好的语句。