『壹』 如何使用go语言的beego框架的orm
models.go
============================
package main
import (
"github.com/astaxie/beego/orm"
)
type User struct {
Id int
Name string
Profile *Profile `orm:"rel(one)"` // OneToOne relation
}
type Profile struct {
Id int
Age int16
User *User `orm:"reverse(one)"` // 设置反向关系(可选)
}
func init() {
// 需要在init中注册定义的model
orm.RegisterModel(new(User), new(Profile))
}
main.go
==============
package main
import (
"fmt"
"github.com/astaxie/beego/orm"
_ "github.com/go-sql-driver/mysql"
)
func init() {
//orm.RegisterModel(new(User))
orm.RegisterDataBase("default", "mysql", "ta3:ta3@/ta3?charset=utf8")
orm.RunSyncdb("default", false, true) // true 改成false,如果表存在则会给出提示,如果改成false则不会提示 , 这句话没有会报主键不存在的错误
}
func main() {
o := orm.NewOrm()
o.Using("default") // 默认使用 default,你可以指定为其他数据库
user := User{Id: 1}
err := o.Read(&user)
if err == orm.ErrNoRows {
fmt.Println("查询不到")
} else if err == orm.ErrMissPK {
fmt.Println("找不到主键")
} else {
fmt.Println(user.Id, user.Name)
}
}
执行结果:
create table `user`
-- --------------------------------------------------
-- Table Structure for `main.User`
-- --------------------------------------------------
CREATE TABLE IF NOT EXISTS `user` (
`id` integer AUTO_INCREMENT NOT NULL PRIMARY KEY,
`name` varchar(255) NOT NULL,
`profile_id` integer NOT NULL UNIQUE
) ENGINE=InnoDB;
create table `profile`
-- --------------------------------------------------
-- Table Structure for `main.Profile`
-- --------------------------------------------------
CREATE TABLE IF NOT EXISTS `profile` (
`id` integer AUTO_INCREMENT NOT NULL PRIMARY KEY,
`age` smallint NOT NULL
) ENGINE=InnoDB;
查询不到
第二次再执行:
table `user` already exists, skip
table `profile` already exists, skip
查询不到
如果 orm.RunSyncdb("default", false, true)改成 orm.RunSyncdb("default", false, false)
则执行结果不会提示。
『贰』 beego orm与原生sql哪个快
collection.find().toArray(function(err,docs){
console.log(docs);
//将数据显示到网页上
// console.log('1'+docs[0].name);
// $('#question').append('<div>'+docs+'</div>');
// document.getElementById("editLevels").value =docs;
『叁』 beego可以像mybatis sql独立出来吗
collection.find().toArray(function(err,docs){
console.log(docs);
//将数来据显自示到网页上
// console.log('1'+docs[0].name);
// $('#question').append('<div>'+docs+'</div>');
// document.getElementById("editLevels").value =docs;
『肆』 beego orm一次最多读多少数据库
举个例子
连接数据库查询表的相版关语句:权
Class.forName("com.microsoft.jdbc.sqlserver.SQLServerDriver");
Connection conn=DriverManager.getConnection("jdbc:microsoft:sqlserver://127.0.0.1:1433;DatabaseName=mytest","sa","123");
Statement stmt=conn.createStatement();
ResultSet rs=stmt.executeQuery("select * from userinfo");
while(rs.next())
『伍』 beego.orm怎么设置数据库名称
目前beego的ORM支持三种数据库:
1.Sqlite
2.PostgreSql
3.MySql
如果要使用其中的数据库必须要把对应内的drive(go语言对于的数据库引容擎)加入到import中:
import (
_ "github.com/go-sql-driver/mysql"
_ "github.com/lib/pq"
_ "github.com/mattn/go-sqlite3"