Can't connect Go to XAMPP MySQL

1.5k views Asked by At

I'm new to Go. I'm trying to use MySQL with Go. I have installed XAMPP which has Apache and MySQL. I'm also using the database/sql package and github.com/go-sql-driver/mysql driver.

I can't figure out the error. I'm using LiteIDE which doesn't show any error but the record is not inserted to my database.

My code is:

// RESTAPI project main.go
package main

import (
    "database/sql"
    "encoding/json"
    "fmt"
    "log"
    "net/http"

    _ "github.com/go-sql-driver/mysql"

    "github.com/gorilla/mux"
)

type API struct {
    Message string "json:message"
}
type User struct {
    ID    int    "json:id"
    Name  string "json:username"
    Email string "json:email"
    First string "json:first"
    Last  string "json:last"
}

func CreateUser(w http.ResponseWriter, r *http.Request) {
    fmt.Fprintln("Create file")
    NewUser := User{}
    NewUser.Name = r.FormValue("user")
    NewUser.Email = r.FormValue("email")
    NewUser.First = r.FormValue("first")
    NewUser.Last = r.FormValue("last")
    output, err := json.Marshal(NewUser)
    fmt.Println(string(output))
    if err != nil {
        fmt.Println("Something went wrong!")
    }
    dsn := "root:password@/dbname"
    db, err := sql.Open("mysql", dsn)
    sql := "INSERT INTO users set user_nickname='" + NewUser.Name + "', user_first='" + NewUser.First + "', user_last='" + NewUser.Last + "', user_email='" + NewUser.Email + "'"
    q, err := db.Exec(sql)
    if err != nil {
        log.Fatal(err)
    }
    fmt.Println(q)
    fmt.Println("User is created")
}

func main() {
    routes := mux.NewRouter()
    routes.HandleFunc("/api/user/create", CreateUser).Methods("GET")
    http.ListenAndServe(":8080", nil)
}
1

There are 1 answers

0
stonith On

As Tom mentioned, you should check for an error after sql.Open:

    db, err := sql.Open("mysql", dsn)
    if err != nil {
        log.Fatal(err)
    }

PS. Never use string concatenations in SQL.

To prevent SQL injections you should use prepared statements:

    sql := "INSERT INTO users set user_nickname='?', user_first='?', user_last='?', user_email='?'"
    q, err := db.Exec(sql, NewUser.Name, NewUser.First, NewUser.Last, NewUser.Email)