/** * 新注册一个ORM对象 */ func NewORM(dbhost, dbport, dbname, dbuser, dbpass, dbcharset string) ORM { link := fmt.Sprintf("%v:%v", dbhost, dbport) db := mysql.New("tcp", "", link, dbuser, dbpass, dbname) err := db.Connect() if err != nil { panic(err) } charsetsql := fmt.Sprintf("set Names %v", dbcharset) db.Query(charsetsql) return ORM{db} }
// Open new connection. The uri need to have the following syntax: // [tcp://addr/]dbname/user/password[?params] // [unix://sockpath/]dbname/user/password[?params] // // Params need to have the following syntax: // key1=val1&key2=val2 // // Key need to have the following value: // charset - used by 'set names' // keepalive - send a PING to mysql server after every keepalive seconds. // // where protocol spercific part may be empty (this means connection to // local server using default protocol). Currently possible forms: // DBNAME/USER/PASSWD?charset=utf8 // unix://SOCKPATH/DBNAME/USER/PASSWD // tcp://ADDR/DBNAME/USER/PASSWD?maxidle=3600 // // If a password contains the slashes (/), use a star (*) to repleace it. // If a password contains the star (*), use double stars (**) to repleace it. // pass/wd => pass*wd // pass*wd => pass**wd func (d *Driver) Open(uri string) (driver.Conn, error) { proto, addr, dbname, user, passwd, params, err := parseDSN(uri) if err != nil { return nil, err } d.proto = proto d.raddr = addr d.user = user d.passwd = passwd d.db = dbname // Establish the connection c := conn{mysql.New(d.proto, d.laddr, d.raddr, d.user, d.passwd, d.db)} if v, ok := params["charset"]; ok { Register("SET NAMES " + v) } if v, ok := params["keepalive"]; ok { t, err := strconv.Atoi(v) if err != nil { return nil, ErrMaxIdle } RegisterFunc(func(my mysql.Conn) { go func() { for my.IsConnected() { time.Sleep(time.Duration(t) * time.Second) if err := my.Ping(); err != nil { break } } }() }) } for _, q := range d.initCmds { c.my.Register(q) // Register initialisation commands } for _, f := range d.initFuncs { c.my.RegisterFunc(f) } if err := c.my.Connect(); err != nil { return nil, errFilter(err) } return &c, nil }
func main() { user := "******" pass := "******" dbname := "test" //proto := "unix" //addr := "/var/run/mysqld/mysqld.sock" proto := "tcp" addr := "127.0.0.1:3306" db := mysql.New(proto, "", addr, user, pass, dbname) fmt.Printf("Connect to %s:%s... ", proto, addr) checkError(db.Connect()) printOK() fmt.Print("Drop A table if exists... ") _, err := db.Start("drop table A") if err == nil { printOK() } else if e, ok := err.(*mysql.Error); ok { // Error from MySQL server fmt.Println(e) } else { checkError(err) } fmt.Print("Create A table... ") checkedResult(db.Query("create table A (name varchar(40), number int)")) printOK() fmt.Print("Insert into A... ") for ii := 0; ii < 10; ii++ { if ii%5 == 0 { checkedResult(db.Query("insert A values (null, null)")) } else { checkedResult(db.Query( "insert A values ('%d*10= %d', %d)", ii, ii*10, ii*100, )) } } printOK() fmt.Println("Select from A... ") rows, res := checkedResult(db.Query("select * from A")) name := res.Map("name") number := res.Map("number") for ii, row := range rows { fmt.Printf( "Row: %d\n name: %-10s {%#v}\n number: %-8d {%#v}\n", ii, "'"+row.Str(name)+"'", row[name], row.Int(number), row[number], ) } fmt.Print("Remove A... ") checkedResult(db.Query("drop table A")) printOK() fmt.Print("Close connection... ") checkError(db.Close()) printOK() }
func main() { user := "******" pass := "******" dbname := "test" //proto := "unix" //addr := "/var/run/mysqld/mysqld.sock" proto := "tcp" addr := "127.0.0.1:3306" db := mysql.New(proto, "", addr, user, pass, dbname) //db.Debug = true fmt.Printf("Connect to %s:%s... ", proto, addr) checkError(db.Connect()) printOK() fmt.Print("Drop 'web' table if exists... ") _, err := db.Start("DROP TABLE web") if err == nil { printOK() } else if e, ok := err.(*mysql.Error); ok { // Error from MySQL server fmt.Println(e) } else { checkError(err) } fmt.Print("Create 'web' table... ") _, err = db.Start("CREATE TABLE web (url VARCHAR(80), content LONGBLOB)") checkError(err) printOK() fmt.Print("Prepare insert statement... ") ins, err := db.Prepare("INSERT INTO web VALUES (?, ?)") checkError(err) printOK() fmt.Print("Prepare select statement... ") sel, err := db.Prepare("SELECT url, OCTET_LENGTH(content) FROM web") checkError(err) printOK() var url string fmt.Print("Bind insert parameters... ") ins.Bind(&url, []byte(nil)) printOK() fmt.Println() for { url = "" fmt.Print("Please enter an URL (blank line terminates input): ") fmt.Scanln(&url) if len(url) == 0 { break } if !strings.Contains(url, "://") { url = "http://" + url } http_res, err := http.Get(url) if err != nil { fmt.Println(err) continue } // Retrieve response directly into database. Use 8 kB buffer. checkError(ins.SendLongData(1, http_res.Body, 8192)) _, err = ins.Run() checkError(err) } fmt.Println() fmt.Print("Select from 'web' table... ") rows, res, err := sel.Exec() checkError(err) printOK() // Print fields names fmt.Println() for _, field := range res.Fields() { fmt.Printf("%-38s ", field.Name) } fmt.Println() fmt.Println("------------------------------------------------------------") // Print result for _, row := range rows { for ii, col := range row { if col == nil { fmt.Print("%-38s ", "NULL") } else { fmt.Printf("%-38s ", row.Bin(ii)) } } fmt.Println() } fmt.Println() fmt.Print("Hit ENTER to exit ") fmt.Scanln() fmt.Print("Remove 'web' table... ") _, err = db.Start("DROP TABLE web") checkError(err) printOK() fmt.Print("Close connection... ") checkError(db.Close()) printOK() }
func main() { user := "******" pass := "******" dbname := "test" //proto := "unix" //addr := "/var/run/mysqld/mysqld.sock" proto := "tcp" addr := "127.0.0.1:3306" db := mysql.New(proto, "", addr, user, pass, dbname) fmt.Printf("Connect to %s:%s... ", proto, addr) checkError(db.Connect()) printOK() fmt.Print("Drop A table if exists... ") _, err := db.Start("drop table A") if err == nil { printOK() } else if e, ok := err.(*mysql.Error); ok { // Error from MySQL server fmt.Println(e) } else { checkError(err) } fmt.Print("Create A table... ") checkedResult(db.Query("create table A (name varchar(40), number int)")) printOK() fmt.Print("Prepare insert statement... ") ins, err := db.Prepare("insert A values (?, ?)") checkError(err) printOK() fmt.Print("Prepare select statement... ") sel, err := db.Prepare("select * from A where number > ? or number is null") checkError(err) printOK() params := struct { txt *string number *int }{} fmt.Print("Bind insert parameters... ") ins.Bind(¶ms) printOK() fmt.Print("Insert into A... ") for ii := 0; ii < 1000; ii += 100 { if ii%500 == 0 { // Assign NULL values to the parameters params.txt = nil params.number = nil } else { // Modify parameters str := fmt.Sprintf("%d*10= %d", ii/100, ii/10) params.txt = &str params.number = &ii } // Execute statement with modified data _, err = ins.Run() checkError(err) } printOK() fmt.Println("Select from A... ") rows, res := checkedResult(sel.Exec(0)) name := res.Map("name") number := res.Map("number") for ii, row := range rows { fmt.Printf( "Row: %d\n name: %-10s {%#v}\n number: %-8d {%#v}\n", ii, "'"+row.Str(name)+"'", row[name], row.Int(number), row[number], ) } fmt.Print("Remove A... ") checkedResult(db.Query("drop table A")) printOK() fmt.Print("Close connection... ") checkError(db.Close()) printOK() }
func New(proto, laddr, raddr, user, passwd string, db ...string) *Conn { return &Conn{ Raw: mysql.New(proto, laddr, raddr, user, passwd, db...), MaxRetries: 7, } }
func main() { user := "******" pass := "******" dbname := "test" //proto := "unix" //addr := "/var/run/mysqld/mysqld.sock" proto := "tcp" addr := "127.0.0.1:3306" db := mysql.New(proto, "", addr, user, pass, dbname) fmt.Printf("Connect to %s:%s... ", proto, addr) checkError(db.Connect()) printOK() fmt.Print("Drop A table if exists... ") _, err := db.Start("drop table A") if err == nil { printOK() } else if e, ok := err.(*mysql.Error); ok { // Error from MySQL server fmt.Println(e) } else { checkError(err) } fmt.Print("Create A table... ") _, err = db.Start("create table A (name varchar(9), number int) engine=InnoDB") checkError(err) printOK() fmt.Print("Prepare insert statement... ") ins, err := db.Prepare("insert A values (?, ?)") checkError(err) printOK() fmt.Print("Prepare select statement... ") sel, err := db.Prepare("select * from A") checkError(err) printOK() fmt.Print("Begining a new transaction... ") tr, err := db.Begin() checkError(err) printOK() tr_ins := tr.Do(ins) fmt.Print("Performing two inserts... ") _, err = tr_ins.Run("jeden", 1) checkError(err) _, err = tr_ins.Run("dwa", 2) checkError(err) printOK() fmt.Print("Commit the transaction... ") checkError(tr.Commit()) printOK() fmt.Print("Begining a new transaction... ") tr, err = db.Begin() checkError(err) printOK() fmt.Print("Performing one insert... ") _, err = tr.Do(ins).Run("trzy", 3) checkError(err) printOK() fmt.Print("Rollback the transaction... ") checkError(tr.Rollback()) printOK() fmt.Println("Select from A... ") rows, res := checkedResult(sel.Exec()) name := res.Map("name") number := res.Map("number") for ii, row := range rows { fmt.Printf("%d: %-10s %-8d\n", ii, row[name], row[number]) } fmt.Print("Remove A... ") checkedResult(db.Query("drop table A")) printOK() fmt.Print("Close connection... ") checkError(db.Close()) printOK() }