Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Error on importing go-sql-driver/sql from github repository

Tags:

mysql

go

As the title says, I have an error when importing go-mysql-driver package. I have installed the go-my-sql driver in my machine but the error still persists. I use XAMPP for local hosting and here’s the block of program.

package model

import (
    "database/sql"
    "fmt"

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

type Table interface {
    Name() string
    Field() ([]string, []interface{})
}

func Connect(username string, password string, host string, database string) (*sql.DB, error) {
    conn := fmt.Sprintf("%s:%s@tcp(%s:3306)/%s", username, password, host, database)
    db, err := sql.Open("mysql", conn)
    return db, err
}

func CreateDB(db *sql.DB, name string) error {
    query := fmt.Sprintf("CREATE DATABASE %v", name)
    _, err := db.Exec(query)
    return err
}

func CreateTable(db *sql.DB, query string) error {
    _, err := db.Exec(query)
    return err
}

func DropDB(db *sql.DB, name string) error {
    query := fmt.Sprintf("DROP DATABASE  %v", name)
    _, err := db.Exec(query)
    return err
}
could not import github.com/go-sql-driver/mysql (no required modules provides package "github.com/go-sql-driver/mysql")

screenshot of what's happening

like image 457
Jarsada Avatar asked Jul 22 '26 05:07

Jarsada


1 Answers

Your IDE is not showing you the whole picture. By running go run main.go (or whatever main file you have) on the command line, you can see the same error as you're seeing on your IDE with some extra:

$ go run main.go
main.go:7:5: no required module provides package github.com/go-sql-driver/mysql; to add it:
    go get github.com/go-sql-driver/mysql

By issuing the suggested command go get github.com/go-sql-driver/mysql, you'll get the dependency added to your go.mod file and the contents of the package will be downloaded to your machine.

Your next execution will work:

$ go run main.go
Hello world

I've made some small modifications to your code to work, I'll add them here for completeness:

  • I've used the same source, but changed the package name to main.
  • I've added a main function to the bottom of the file:
func main() {
    fmt.Println("Hello world")

    _, err := Connect("username", "password", "localhost", "db")

    if err != nil {
        panic(err)
    }
}
  • I've saved to a file named main.go
  • I've initialized the go.mod file by running go mod init test and go mod tidy, then I took the steps described on the beginning of the answer.
like image 126
Sergio Moura Avatar answered Jul 23 '26 19:07

Sergio Moura



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!