Feedback my working on a Go package for X

Hi,

I’m working on a Go package for X. Can anyone review my code?

package main

import (
	"database/sql"
	"fmt"
	"log"

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

func main() {
	db, err := sql.Open("mysql", "user:password@tcp(database-server:3306)/database-name")
	if err != nil {
		log.Fatal(err)
	}
	defer db.Close()

	var (
		id   int
		name string
		age  int
	)

	rows, err := db.Query("SELECT id, name, age FROM users WHERE age > ?", 18)
	if err != nil {
		log.Fatal(err)
	}
	defer rows.Close()

	for rows.Next() {
		err := rows.Scan(&id, &name, &age)
		if err != nil {
			log.Fatal(err)
		}
		fmt.Printf("ID: %d, Name: %s, Age: %d\n", id, name, age)
	}

	err = rows.Err()
	if err != nil {
		log.Fatal(err)
	}
}

Thank you in advance.

Hello Garg,
I think your code is great. :rocket:

You can do some adjustments, creating a struct called User for id, name, age outside context and initiate u := User{} for example.

defer rows.Close() I understand you can remove it because it is automatic close when the row is empty. But closing you can solve enumerating, but can’t understand when this can happen, maybe someone with more experience can add more comments.

Next steps you can create functions like selectUserByAge(db *sql.DB, int age) (*User, error)

Hey @tonnytg,

Thank you for reply. I really appreciate your support.

Don’t hardcode connection information in the go file.
Put the connection parameters in a file and read that file.
Most programs need configuration parameters, so you can put the connection string as a parameter in such a file.

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.