Created
November 11, 2024 15:48
-
-
Save bukakoding/bf401b7344f114fd110dca1fd1a6002c to your computer and use it in GitHub Desktop.
Fetching query dynamically with Golang
This file contains 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
package main | |
import ( | |
"database/sql" | |
"fmt" | |
"log" | |
_ "github.com/go-sql-driver/mysql" | |
) | |
func main() { | |
dsn := "user:password@tcp(127.0.0.1:3306)/testdb" | |
db, err := sql.Open("mysql", dsn) | |
if err != nil { | |
log.Fatalf("Error opening database connection: %v", err) | |
} | |
defer db.Close() | |
// Test connection | |
err = db.Ping() | |
if err != nil { | |
log.Fatalf("Error pinging database: %v", err) | |
} | |
fmt.Println("Successfully connected to the database!") | |
// SQL Query | |
query := "SELECT id, name, age, email FROM users" | |
rows, err := db.Query(query) | |
if err != nil { | |
log.Fatalf("Error executing query: %v", err) | |
} | |
defer rows.Close() | |
// Get column names | |
columns, err := rows.Columns() | |
if err != nil { | |
log.Fatalf("Failed to get column names: %v", err) | |
} | |
// Create slices for holding row data | |
var rowData []interface{} | |
for rows.Next() { | |
rowData = make([]interface{}, len(columns)) | |
rowPointers := make([]interface{}, len(columns)) | |
for i := range rowData { | |
rowPointers[i] = &rowData[i] | |
} | |
if err := rows.Scan(rowPointers...); err != nil { | |
log.Printf("Failed to scan row: %v", err) | |
continue | |
} | |
// Print data dynamically based on column names | |
for i, data := range rowData { | |
// Check if data is not nil before printing | |
if data != nil { | |
switch v := data.(type) { | |
case []byte: | |
fmt.Printf("%s: %s\n", columns[i], v) | |
default: | |
fmt.Printf("%s: %v\n", columns[i], v) | |
} | |
} | |
} | |
fmt.Println("---") // Separator between rows | |
} | |
// Check for errors after iteration | |
if err := rows.Err(); err != nil { | |
log.Printf("Error in rows: %v", err) | |
} | |
fmt.Println("Database operations completed.") | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment