Go Language
Go Language

MySQL to Struct in Go Language


Here’s an example of creating a new struct object from a MySQL query. The function below will fetch a user based on the userId (int) submitted. Look at the bottom of this post to see how to Fetch an array of each user in database. I have also include a MySQL dump of the Users table.

User struct

1
2
3
4
5
type User struct {
	Id            int       `json:"id"`
	Name          string    `json:"name"`
	Email         string    `json:"email"`
}

Fetching User Function (creating User) (Table: users – Columns: id,name,email)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
// import "database/sql"
 
var db *sql.DB
 
func main() {
   // replace the information below to match your MySQL login and database
   db, _ = sql.Open("mysql", "root:[email protected](localhost:3306)/mydatabase")
}
 
func FetchUser(userId int) User {
	rows := db.QueryRow("SELECT id,email,name FROM users WHERE id=?", userId)
	var id int
	var name, email string
	var user User
	err := rows.Scan(&id, &email, &name)
	if err != nil {
		if err == sql.ErrNoRows {
                       // no such user id
		} else {
			panic(err)
		}
	} else {
		user = User{Id: id, Name: name, Email: email}
	}
	return user
}

Using the function in script

1
2
thisUser := FetchUser(5)
fmt.Println(thisUser.Email)

Example of Fetching All Users

1
2
3
4
5
6
7
8
9
10
11
12
13
14
func FetchAllUsers() []User {
	rows, _ := db.Query("SELECT id,email,name FROM users")
	var id int
	var name, email string
	var users []User
 
	for rows.Next() {
		err := rows.Scan(&id, &name, &email)
		if err != nil { /* error handling */}
		users = append(users, User{Id: id, Email: email, Name: name})
	}
 
	return users
}

Print out how many users are in database

1
fmt.Println("Total amount of Users: ", len(FetchAllUsers()))

MySQL Dump of Users table

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
CREATE TABLE IF NOT EXISTS `users` (
  `id` int(11) NOT NULL,
  `email` text NOT NULL,
  `name` text NOT NULL
) ENGINE=MyISAM AUTO_INCREMENT=7 DEFAULT CHARSET=utf8;
 
INSERT INTO `users` (`id`, `email`, `name`) VALUES
(5, [email protected]', 'Example User'),
(6, [email protected]', 'Another User');
 
ALTER TABLE `users`
  ADD PRIMARY KEY (`id`);
 
ALTER TABLE `users`
  MODIFY `id` int(11) NOT NULL AUTO_INCREMENT,AUTO_INCREMENT=7;

View Comments
There are currently no comments.