O
O
Oleg Voitenko2018-04-20 14:13:00
MySQL
Oleg Voitenko, 2018-04-20 14:13:00

How to correctly access a database in Go using the structure described below?

the second day I can’t figure out how to code correctly.
Task:
we have a User Structure, login and password from the front come into it.

type User struct {
  Username string `json:"username"`
  Password string `json:"password"`
}

I need to get the id of this user from MySQL, I do this:
package ui

import (
  "encoding/json"
  "fmt"
  "net"
  _ "github.com/lib/pq"
  _ "github.com/go-sql-driver/mysql"
  "database/sql"
  "github.com/jmoiron/sqlx"



)

type User struct {
  Username string `json:"username"`
  Password string `json:"password"`
}

type db interface {
  SelectUsers() ([]*User, error)
}

type Model struct {
  db
}

type myDb struct {
  dbConn *sqlx.DB
  sqlSelectUsers  *sqlx.Stmt
  sqlSelectUser   *sqlx.Rows
}


func New(db db) *Model {
  return &Model{
    db: db,
  }
}

func (m *Model) Users() ([]*User, error) {
    return m.SelectUsers()
}
//****************************************//
//*коннект к бд, все работает ок.*//
//***************************************//
func InitDb(cfg Config) (*myDb, error) {
  if dbConn, err := sqlx.Connect("mysql", cfg.ConnectString); err != nil {
    return nil, err
  } else {
    p := &myDb{dbConn: dbConn}
    if err := p.dbConn.Ping(); err != nil {
      return nil, err
    }
    if err := p.prepareSqlStatements(); err != nil {
      return nil, err
    }
    return p, nil
  }
}

func (p *myDb) prepareSqlStatements() (err error) {
if p.sqlSelectUsers, err = p.dbConn.Preparex(
    "SELECT login, pass, id FROM users WHERE login=? AND pass=?",
  ); err != nil {
    return err
  }
}

func (p *myDb) SelectUsers() ([]*model.User, error) {
  user := make([]*model.User, 0)
  if err := p.sqlSelectUsers.Select(&user); err != nil {
    return nil, err
  }
  return user, nil
}

usr, err := m.Users()
 js, err := json.Marshal(usr)
        		if err != nil {
        			http.Error(w, "This is an error2", http.StatusBadRequest)
        			return
        		}

        		fmt.Fprintf(w, string(js))

The code works but removes all users from the database, but it's stressful for me.
So that's the question, how can I extract the user by login, password
The problem is that I can't figure out how to pass the values ​​of the User structure to the function in order to substitute them after WHERE.
I will only be grateful for any kicks, because after the puff, you need to understand this language a little differently.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
P
Papa, 2018-04-20
Stifflera @PapaStifflera

Learn to use search engines and documentation.
Everything is in the examples: https://github.com/go-sql-driver/mysql/wiki/Examples

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question