ORM MySql Connection Error

I am use beego framework. I am getting the error "Must have one register DataBase alias nameddefault "in ORM mysql connection

create this file for your model, get the commands sql and execute in your database.

model/model.go

package model

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

//create database orm_test;
//create table user ( id integer primary key, name varchar(255), profile_id integer );
type User struct {
	Id          int
	Name        string
	Profile     *Profile   `orm:"rel(one)"` // OneToOne relation
}

//create table profile ( id integer primary key, age integer, user integer );
type Profile struct {
	Id          int
	Age         int16
	User        *User   `orm:"reverse(one)"` // Reverse relationship (optional)
}

func init() {
	// Need to register model in init
	orm.RegisterModel(new(User), new(Profile))
}

the file main

main.go

package main

import (
	"fmt"
	"github.com/astaxie/beego/orm"
	_ "github.com/go-sql-driver/mysql"
	"golangbridge/2/model"
)

func init() {
	orm.RegisterDriver("mysql", orm.DRMySQL)
	orm.RegisterDataBase("default", "mysql", "root:123456@/orm_test?charset=utf8")
}

func main() {
	o := orm.NewOrm()
	o.Using("default") // Using default, you can use other database

	profile := new(model.Profile)
	profile.Age = 30
	profile.Id = 1

	user := new(model.User)
	user.Profile = profile
	user.Name = "slene"
	user.Id = 1

	fmt.Println(o.Insert(profile))
	fmt.Println(o.Insert(user))
}

execute the main file

go run main.go

return

0 <nil>
0 <nil>
1 Like

Change the code only with your name of package “golangbridge/2/model” and your access for your database.

thank you for your help

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.