Go database connection method, configuration Independent

Source: Internet
Author: User
This is a creation in Article, where the information may have evolved or changed.
Adjust as needed, the configuration is saved separately in the configuration file, the required package is downloaded in the import
package Utilimport ("Database/sql" "Fmt" _ "Github.com/go-sql-driver/mysql" "Github.com/robfig/config") var (DB_NAME,DB_USER, Db_pass,db_host,db_port string) Func init () {c, _: = Config. Readdefault ("Config/config.ini") db_user, _ = c.string ("db", "Db_user") db_pass, _ = c.string ("db", "Db_pass") db_host, _ = C.string ("db", "Db_host") db_name, _ = c.string ("db", "db_name") db_port, _ = c.string ("db", "Db_port") fmt. Println ("\ n current server IP and port:", Db_host, Db_port, Db_user, Db_pass, db_name)}func getdbconnetion (DB *sql.) DB, errstr error) {db, err: = SQL. Open ("MySQL", FMT.) Sprintf ("%s:%s@tcp (%s:%s)/%s?charset=utf8", Db_user, Db_pass, Db_host, Db_port, db_name)) if err! = Nil {fmt. Println ("\nconnection mysql error") return DB, Err}//defer db. Close () db. Setmaxopenconns (+) db. Setmaxidleconns (+) Err = db. Ping () if err! = Nil {fmt. Println ("\nopen mysql error", err) return db, Err}return db, nil} 

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.