2
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

BeegoのORMの使い方(RAWで生のSQLを書く)

Last updated at Posted at 2019-11-12

これはGolangのフレームワークBeegoで生のSQLを書きたいときに参考にできるソース

だれかBeegoのSQLインジェクションの詳細を調べてほしい…

公式サイト
Beego Raw

・やっとくといいこと(Beegoのormをデバックモードにする)
 →これをすると発行されるSQLを確認できる。

// これをconf/xxx.confとかに書いておくと環境別に分けられる
// database.debug = true

debug, _:= beego.AppConfig.Bool("database.debug");
if (debug == true) {
	orm.Debug = true
}

Raw関数を使用して直接SQLを発行

package models

import (
	_ "errors"
	"fmt"
	_ "strings"

	"github.com/astaxie/beego"
	"github.com/astaxie/beego/orm"
)

type User struct {
	Id       int
	Name     string `orm:"size(128)"`
	UserName string `orm:"size(128)"`
	Email    string `orm:"size(128)"`
	Token    string `orm:"size(128)"`
	Avatar   string `orm:"size(128)"`
}

func init() {
	orm.RegisterModel(new(User))
}

// 使用するサービス関数
func GetUserByEmail(email string)(v *User, err error) {
	// ほかのORM同様にnewする
	o := orm.NewOrm()
	// Raw関数を使用してSQLを発行
	err = o.Raw("SELECT * FROM user where email = ?", email).QueryRow(&v)
	if err == nil {
	}else{
		beego.Error(err)
		return nil, err
	}
	return v, nil
}

NewQueryBuilderを使う

func LoginSubmit(username string, email string)(user *User, err error) {

	qb, _ := orm.NewQueryBuilder("mysql")
	qb.Select("*").From("user_d_b").Where(fmt.Sprintf("name='%s'", username)).And(fmt.Sprintf("email='%s'", email))
	sql := qb.String()
	o.Raw(sql).QueryRow(&userDB)
	if user.Id == 0 {
		return false
	}
	return true
}
2
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?