package datasource

import (
	"WorldEpcho/src/config"
	"database/sql"
	"fmt"
	_ "github.com/go-sql-driver/mysql"
	"github.com/go-xorm/xorm"
	"log"
)

var (
	DB     *sql.DB
	Engine *xorm.Engine
)

func InitMysql() {
	fmt.Println("InitMysql....")

	// xorm 连接数据库
	var err error
	Engine, err = xorm.NewEngine("mysql", config.Conf.Mysql_UserName+":"+config.Conf.Mysql_PWD+"@tcp("+config.Conf.DBserver+":"+config.Conf.MysqlPort+")/"+config.Conf.DBname+"?charset=utf8")

	fmt.Println(" ============== 【xorm 连接数据库】 =====================   ")
	println("xorm 连接数据库,Engine: ", Engine)
	fmt.Println(" ============== 【xorm 连接数据库】 =====================   ")

	if err != nil {
		log.Println("数据库连接失败:", err)
		fmt.Println("数据库连接失败:", err)
		return
	}

}

//操作数据库
func ModifyDB(sql string, args ...interface{}) (int64, error) {
	result, err := DB.Exec(sql, args...)
	if err != nil {
		log.Println(err)
		return 0, err
	}
	count, err := result.RowsAffected()
	if err != nil {
		log.Println(err)
		return 0, err
	}
	return count, nil
}

//创建用户表
func CreateTableWithUser() {
	sql := `CREATE TABLE IF NOT EXISTS users(
		id INT(4) PRIMARY KEY AUTO_INCREMENT NOT NULL,
		username VARCHAR(64),
		password VARCHAR(64),
		status INT(4),
		createtime INT(10)
		);`

	ModifyDB(sql)

}

//查询
func QueryRowDB(sql string) *sql.Row {
	return DB.QueryRow(sql)
}
