• Go 连接docker 数据库


    连接 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)
        }
    }
    
  • 相关阅读:
    hdu1074Doing Homework
    1088滑雪
    hdu1078FatMouse and Cheese
    hdu1058Humble Numbers
    hdu1114 Piggy-Bank
    hdu1069Monkey and Banana
    未解决的问题_c#中,最小化触发事件
    WPF Button 样式资源设置&后台生成button样式
    .NET 调用外部exe程序,出现已停止工作
    json类序列化与反序列化参考
  • 原文地址:https://www.cnblogs.com/MasonHu/p/14778980.html
Copyright © 2020-2023  润新知