简体   繁体   中英

How to create a MySQL database (table) in Go and perform CRUD operations

I have imported the drivers from github.com/go-sql-driver/mysql and have successfully established connection to the database. I just want to start creating a table and be able to update, fetch and delete data from it Other resources I've seen seem to skip this part or are just unclear about it (they seem to start fetching the data and I'm like..where did the data come from, how did they create it) and I just want clear explanations thanks.

// main.go
package main

import (
    "database/sql"
    "fmt"
    _ "github.com/go-sql-driver/mysql"
)

func main() {
    db, err := sql.Open("mysql", "user:password@tcp(127.0.0.1:3306)/dbname")
    if err != nil {
        panic(err)
    }
    defer db.Close()
}

Update 16/05/2020:
It turns out that I never even knew a database server had to be running in the first place as @mkopriva pointed out in the comments (I guess this was the initial source of my challenge...now I'm like what else was I suppose to even connect to...duh...lol)
PS firewall was not an issue in my case.

You can use the methods Exec , Query , and QueryRow that are provided by *sql.DB to send your SQL commands to the connected database.

func main() {
    db, err := sql.Open("mysql", "user:password@tcp(127.0.0.1:3306)/dbname")
    if err != nil {
        panic(err)
    } else if err = db.Ping(); err != nil {
        panic(err)
    }
    defer db.Close()

    _, err := db.Exec("CREATE TABLE IF NOT EXISTS mytable (id BIGINT NOT NULL AUTO_INCREMENT PRIMARY KEY, some_text TEXT NOT NULL)")
    if err != nil {
        panic(err)
    }

    // Create
    res, err := db.Exec("INSERT INTO mytable (some_text) VALUES (?)", "hello world")
    if err != nil {
        panic(err)
    }

    // get the id of the newly inserted record
    id, err := res.LastInsertId()
    if err != nil {
        panic(err)
    }

    // Read
    var someText string
    row := db.QueryRow("SELECT some_text FROM mytable WHERE id = ? LIMIT 1", id)
    if err := row.Scan(&someText); err != nil {
        panic(err)
    }
    fmt.Println(someText)

    // Update
    _, err = db.Exec("UPDATE mytable SET some_text = ? WHERE id = ?", "Hello, 世界", id)
    if err != nil {
        panic(err)
    }

    // Delete
    _, err = db.Exec("DELETE FROM mytable WHERE id = ?", id)
    if err != nil {
        panic(err)
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM