连接 Mysql
package introduction1
import (
"database/sql"
"fmt"
_ "github.com/go-sql-driver/mysql"
)
func ConnMysql() {
connStr := "root:passwd@tcp(192.168.234.129:3311)/djweb"
db, err := sql.Open("mysql", connStr)
if err != nil {
fmt.Printf("Connect mysql fail: %s
", err)
} else { // 连接成功
fmt.Println("Connect to mysql success")
}
defer db.Close()
sqlQuery := "select * from user"
rows, err := db.Query(sqlQuery)
if err != nil {
fmt.Printf("select fail: %s
", err)
}
// var mapUser map[string]int
// mapUser = make(map[string]int)
// var mapUser = make(map[string]int)
for rows.Next() {
var id int
rows.Columns()
err := rows.Scan(&id)
if err != nil {
fmt.Printf("get user info error: %s
", err)
}
fmt.Println(id)
}
// for k, v := range mapUser {
// fmt.Println(k, v)
// }
}
连接 Redis
package introduction1
import (
"fmt"
"github.com/go-redis/redis"
)
// 初始化一个redis全局客户端对象
var redisDB *redis.Client
func RedisConn()(err error) {
// cl, err := redis.Dial("tcp", "192.168.234.129:6379")
redisDB = redis.NewClient(&redis.Options{
Addr: "192.168.234.129:6379",
// Addr: "127.0.0.1:6379",
Password: "",
DB: 0,
})
_, err = redisDB.Ping().Result()
if err != nil {
return err
}
return nil
}
func RedisExample() {
err := redisDB.Set("score", 100, 0).Err()
if err != nil {
fmt.Printf("Set score failed, err: %v
", err)
return
}
val, err := redisDB.Get("score").Result()
if err != nil {
fmt.Printf("get score failed, err:%v
", err)
return
}
fmt.Println("score", val)
val2, err := redisDB.Get("name").Result()
if err == redis.Nil {
fmt.Println("name does not exist")
} else if err != nil {
fmt.Printf("get name failed, err:%v
", err)
return
} else {
fmt.Println("name", val2)
}
}