『壹』 如何使用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"