CREATE TABLE `person` ( `user_id` int(128) DEFAULT NULL, `username` varchar(255) DEFAULT NULL, `sex` varchar(16) DEFAULT NULL, `email` varchar(128) DEFAULT NULL ) ENGINE=InnoDB DEFAULT CHARSET=utf8
栗子(insert)
package main import ( _ ) type Person struct { UserId ` Username ` Sex ` Email ` } var Db *sqlx.DB func init() { database, err := sqlx.Open(, ) if err != nil { fmt.Println(, err) return } Db = database } func main() { r, err := Db.Exec(, , , ) if err != nil { fmt.Println(, err) return } id, err := r.LastInsertId() if err != nil { fmt.Println(, err) return } fmt.Println(, id) }
栗子(update)
package main import ( _ ) type Person struct { UserId ` Username ` Sex ` Email ` } var Db *sqlx.DB func init() { database, err := sqlx.Open(, ) if err != nil { fmt.Println(, err) return } Db = database } func main() { _, err := Db.Exec(, ) if err != nil { fmt.Println(, err) return } }
栗子(select)
package main import ( _ ) type Person struct { UserId ` Username ` Sex ` Email ` } type Place struct { Country ` City ` TelCode ` } var Db *sqlx.DB func init() { database, err := sqlx.Open(, ) if err != nil { fmt.Println(, err) return } Db = database } func main() { var person []Person err := Db.Select(&person, , 1) if err != nil { fmt.Println(, err) return } fmt.Println(, person) people := []Person{} Db.Select(&people, ) fmt.Println(people) jason, john := people[0], people[1] fmt.Printf(, jason, john) }
栗子(delete)
package main import ( _ ) type Person struct { UserId ` Username ` Sex ` Email ` } var Db *sqlx.DB func init() { database, err := sqlx.Open(, ) if err != nil { fmt.Println(, err) return } Db = database } func main() { _, err := Db.Exec(, ) if err != nil { fmt.Println(, err) return } fmt.Println() }
RabbitMQ
安装
go
文档:
https://github.com/rabbitmq/rabbitmq-tutorials/tree/master/go
栗子一(普通模式) 生产者:
package main import ( ) /* 默认点对点模式 */ func failOnError(err error, msg string) { if err != nil { log.Fatalf(, msg, err) panic(fmt.Sprintf(, msg, err)) } } func main() { // 连接 conn, err := amqp.Dial() failOnError(err, ) defer conn.Close() // 打开一个并发服务器通道来处理消息 ch, err := conn.Channel() failOnError(err, ) defer ch.Close() // 申明一个队列 q, err := ch.QueueDeclare( , , , , , // no-wait nil, // arguments ) failOnError(err, ) body := bodyFrom(os.Args) // 发布 err = ch.Publish( "", // exchange 默认模式,exchange为空 q.Name, , , amqp.Publishing{ // 持久性的发布,因为队列被声明为持久的,发布消息必须加上这个(可能不用),但消息还是可能会丢,如消息到缓存但MQ挂了来不及持久化。 DeliveryMode: amqp.Persistent, ContentType: , Body: []byte(body), }) failOnError(err, ) log.Printf(, body) } func bodyFrom(args []string) string { var s string if (len(args) < 2) || os.Args[1] == "" { s = fmt.Sprintf(,, time.Now()) } else { s = strings.Join(args[1:], " ") } return s }
消费者: