Datenbanken, erster Versuch
This commit is contained in:
parent
b26544756a
commit
766aedf22d
21 changed files with 678 additions and 320 deletions
67
repositories/course.go
Normal file
67
repositories/course.go
Normal file
|
@ -0,0 +1,67 @@
|
|||
// course
|
||||
package repositories
|
||||
|
||||
import (
|
||||
"database/sql"
|
||||
"sprechstundentool/models"
|
||||
)
|
||||
|
||||
type CourseRepo struct {
|
||||
db *sql.DB
|
||||
}
|
||||
|
||||
func NewCourseRepo(db *sql.DB) *CourseRepo {
|
||||
return &CourseRepo{
|
||||
db: db,
|
||||
}
|
||||
}
|
||||
|
||||
func (r *CourseRepo) FindByName(name string) (models.Course, error) {
|
||||
row := r.db.QueryRow("SELECT * FROM course WHERE name=?", name)
|
||||
var course models.Course
|
||||
if err := row.Scan(&course.Id, &course.Name); err != nil {
|
||||
return models.Course{}, err
|
||||
}
|
||||
return course, nil
|
||||
}
|
||||
|
||||
func (r *CourseRepo) FindById(id int) (models.Course, error) {
|
||||
row := r.db.QueryRow("SELECT * FROM course WHERE id=?", id)
|
||||
var course models.Course
|
||||
if err := row.Scan(&course.Id, &course.Name); err != nil {
|
||||
return models.Course{}, err
|
||||
}
|
||||
return course, nil
|
||||
}
|
||||
|
||||
func (r *CourseRepo) GetAll() ([]models.Course, error) {
|
||||
rows, err := r.db.Query("SELECT * FROM course")
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer rows.Close()
|
||||
|
||||
return r.getFromRows(rows)
|
||||
}
|
||||
|
||||
func (r *CourseRepo) GetActive() ([]models.Course, error) {
|
||||
rows, err := r.db.Query("SELECT * FROM course WHERE active")
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer rows.Close()
|
||||
|
||||
return r.getFromRows(rows)
|
||||
}
|
||||
|
||||
func (r *CourseRepo) getFromRows(rows *sql.Rows) ([]models.Course, error) {
|
||||
var courses []models.Course
|
||||
for rows.Next() {
|
||||
var course models.Course
|
||||
if err := rows.Scan(&course.Id, &course.Name); err != nil {
|
||||
return courses, err
|
||||
}
|
||||
courses = append(courses, course)
|
||||
}
|
||||
return courses, nil
|
||||
}
|
Loading…
Add table
Add a link
Reference in a new issue