Last active
April 30, 2025 16:37
-
-
Save evilnapsis/8e0600c9b4be2af96aae3942b69cbebc to your computer and use it in GitHub Desktop.
Conectar Go con MySQL
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| // Author @evilnapsis | |
| package main | |
| import "fmt" | |
| import "github.com/go-sql-driver/mysql" | |
| import "database/sql" | |
| // creamos la estructura o clase donde se guardaran los resultados | |
| type Tabla struct { | |
| name string | |
| } | |
| var db *sql.DB | |
| var rows *sql.Rows | |
| func main(){ | |
| fmt.Println("Probando MySQL in go...") | |
| // seccion1. Codigo para configurar la conexion a la base de datos | |
| cfg := mysql.NewConfig() | |
| cfg.User = "root" | |
| cfg.Passwd = "" | |
| cfg.Addr = "127.0.0.1:3306" | |
| cfg.DBName = "inventiolite" | |
| // seccion 2. realizamos la conexion y si hay algun error lo mostramos | |
| var err error | |
| db, err = sql.Open("mysql", cfg.FormatDSN()) | |
| if err != nil{ | |
| //log.Fatal(err) | |
| } | |
| fmt.Println("conectado!") | |
| var tablas []Tabla | |
| // seccion 3. ejecutamos la consulta, en este caso mostrar las tablas de la DB | |
| rows, err = db.Query("show tables") | |
| if err!= nil { | |
| fmt.Errorf("error del SQL") | |
| } | |
| // seccion 4. hacemos un recorrido de los resultados | |
| for rows.Next(){ | |
| var tabl Tabla | |
| if err := rows.Scan(&tabl.name); err!=nil{ | |
| fmt.Errorf("prueba : %v", err) | |
| } | |
| tablas = append(tablas, tabl) | |
| } | |
| // seccion 5. recorremos y mostramos los resultados | |
| for tb := range tablas{ | |
| fmt.Println("tabla: ", tablas[tb].name) | |
| } | |
| rows.Close() // cerramos la lectura | |
| db.Close() // cerramos la conexion | |
| //fmt.Println("%+v", tablas) | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment