github.com/giovannyortegon/go@v0.0.0-20220115155912-8890063f5bdd/src/WebProfesional/5-GoMySql/models/users.go (about) 1 package models 2 3 import ( 4 "gomysql/db" 5 ) 6 7 type User struct { 8 Id int64 9 UserName string 10 Password string 11 Email string 12 } 13 14 type Users []User 15 16 const UserSchema string = `CREATE TABLE users ( 17 id INT(6) UNSIGNED AUTO_INCREMENT PRIMARY KEY, 18 username VARCHAR(30) NOT NULL, 19 password VARCHAR(100) NOT NULL, 20 email VARCHAR(50), 21 create_data TIMESTAMP DEFAULT CURRENT_TIMESTAMP)` 22 23 //constructor usuario 24 func NewUser(username string, password string, email string) *User { 25 user := &User{UserName: username, Password: password, Email: email} 26 27 return user 28 } 29 30 // crear usuario e insertar a db 31 func CreateUser(username string, password string, email string) *User { 32 user := NewUser(username, password, email) 33 user.Save() 34 35 return user 36 } 37 38 // Crear usuario e insert 39 func (user *User) insert() { 40 sql := "INSERT users SET username=?, password=?, email=?" 41 result, _ := db.Exec(sql, user.UserName, user.Password, user.Email) 42 user.Id, _ = result.LastInsertId() 43 } 44 45 func ListUsers() Users { 46 sql := "SELECT id, username, password, email FROM users" 47 users := Users{} 48 rows, _ := db.Query(sql) 49 50 for rows.Next() { 51 user := User{} 52 rows.Scan(&user.Id, &user.UserName, &user.Password, &user.Email) 53 users = append(users, user) 54 } 55 56 return users 57 } 58 59 // Obtener un registro 60 func GetUser(id int) *User { 61 user := NewUser("", "", "") 62 sql := "SELECT id, username, password, email FROM users WHERE id=?" 63 rows, _ := db.Query(sql, id) 64 65 for rows.Next() { 66 rows.Scan(&user.Id, &user.UserName, &user.Password, &user.Email) 67 } 68 69 return user 70 } 71 72 func (user *User) update() { 73 sql := "UPDATE users SET username=?, password=?, email=? WHERE id=?" 74 db.Exec(sql, user.UserName, user.Password, user.Email, user.Id) 75 } 76 77 func (user *User) Save() { 78 if user.Id == 0 { 79 user.insert() 80 } else { 81 user.update() 82 } 83 } 84 85 // Eliminar un registro 86 func (user *User) Delete() { 87 sql := "DELETE FROM users WHERE id=?" 88 db.Exec(sql, user.Id) 89 }