How to connect golang to mysql database
golang operation mysql
Installation
go get "github.com/go-sql-driver/mysql" go get "github.com/jmoiron/sqlx"
Connect database
var Db *sqlx.DB db, err := sqlx.Open("mysql","username:password@tcp(ip:port)/database?charset=utf8") Db = db
Connection 2
package main import ( "database/sql" "fmt" _ "github.com/go-sql-driver/mysql" ) var db *sql.DB //全局对象db func initDB() (err error) { db, err = sql.Open("mysql","root:admin123@tcp(127.0.0.1:3306)/dududu?charset=utf8") if err!=nil{ return err } err = db.Ping() //校验数据库连接 if err!=nil{ return err } return nil } type beautiful struct { spu_id string title string price string } func queryRowDemo() { sqlStr :="select spu_id,title,price from dududu_shops where id = ?" var u beautiful err:=db.QueryRow(sqlStr,101).Scan(&u.spu_id,&u.title,&u.price) if err!=nil{ fmt.Println("2",err) } fmt.Println(u) } func main() { err:=initDB() if err!=nil{ fmt.Println("1",err) return } queryRowDemo() }
Handle Types
The sqlx design and database/sql usage methods are the same. Contains 4 main handle types:
sqlx.DB - similar to sql.DB, represents the database.
sqlx.Tx - Similar to sql.Tx, it represents things.
sqlx.Stmt - Similar to sql.Stmt, it represents prepared statement.
sqlx.NamedStmt - represents prepared statement (supports named parameters)
All handler types provide compatibility with database/sql, This means that when you call sqlx.DB.Query, you can directly replace it with sql.DB.Query. This makes sqlx easy to add to existing database projects.
In addition, sqlx has two cursor types:
sqlx.Rows - Similar to sql.Rows, Queryx returns.
sqlx.Row - Similar to sql.Row, QueryRowx returns.
Compared with the database/sql method, there is a new syntax, which means that the obtained data can be directly converted into a structure.
Get(dest interface{}, …) error
Select(dest interface{}, …) error
Create a table
All the following examples use the following table structure as the basis for operation.
CREATE TABLE `userinfo` ( `uid` INT(10) NOT NULL AUTO_INCREMENT, `username` VARCHAR(64) DEFAULT NULL, `password` VARCHAR(32) DEFAULT NULL, `department` VARCHAR(64) DEFAULT NULL, `email` varchar(64) DEFAULT NULL, PRIMARY KEY (`uid`) )ENGINE=InnoDB DEFAULT CHARSET=utf8
Exec uses
Exec and MustExec will take out a connection from the connection pool and then perform the corresponding query operation. For drivers that do not support ad-hoc query execution, a prepared statement is created behind the operation execution. This connection will be returned to the connection pool before the result is returned.
It should be noted that different database types use different placeholders. What does mysql use? as a placeholder symbol.
MySQL used?
PostgreSQL uses 1,1,2 etc.
SQLite uses? Or $1
- ##Oracle use: name
package main import ( _ "github.com/go-sql-driver/mysql" "github.com/jmoiron/sqlx" "fmt" ) var Db *sqlx.DB func init() { db, err := sqlx.Open("mysql", "stu:1234qwer@tcp(10.0.0.241:3307)/test?charset=utf8") if err != nil { fmt.Println("open mysql failed,", err) return } Db = db } func main() { result, err := Db.Exec("INSERT INTO userinfo (username, password, department,email) VALUES (?, ?, ?,?)","wd","123","it","wd@163.com") if err != nil{ fmt.Println("insert failed,error: ", err) return } id,_ := result.LastInsertId() fmt.Println("insert id is :",id) _, err1 := Db.Exec("update userinfo set username = ? where uid = ?","jack",1) if err1 != nil{ fmt.Println("update failed error:",err1) } else { fmt.Println("update success!") } _, err2 := Db.Exec("delete from userinfo where uid = ? ", 1) if err2 != nil{ fmt.Println("delete error:",err2) }else{ fmt.Println("delete success") } } //insert id is : 1 //update success! //delete success
stmt, err := db.Prepare(`SELECT * FROM place WHERE telcode=?`) row = stmt.QueryRow(65) tx, err := db.Begin() txStmt, err := tx.Prepare(`SELECT * FROM place WHERE telcode=?`) row = txStmt.QueryRow(852)
stmt, err := db.Preparex(`SELECT * FROM place WHERE telcode=?`) var p Place err = stmt.Get(&p, 852)
package main import ( _ "github.com/go-sql-driver/mysql" "github.com/jmoiron/sqlx" "fmt" ) var Db *sqlx.DB func init() { db, err := sqlx.Open("mysql", "stu:1234qwer@tcp(10.0.0.241:3307)/test?charset=utf8") if err != nil { fmt.Println("open mysql failed,", err) return } Db = db } func main() { rows, err := Db.Query("SELECT username,password,email FROM userinfo") if err != nil{ fmt.Println("query failed,error: ", err) return } for rows.Next() { //循环结果 var username,password,email string err = rows.Scan(&username, &password, &email) println(username,password,email) } } //wd 123 wd@163.com //jack 1222 jack@165.com
package main import ( _ "github.com/go-sql-driver/mysql" "github.com/jmoiron/sqlx" "fmt" ) var Db *sqlx.DB type stu struct { Username string `db:"username"` Password string `db:"password"` Department string `db:"department"` Email string `db:"email"` } func init() { db, err := sqlx.Open("mysql", "stu:1234qwer@tcp(10.0.0.241:3307)/test?charset=utf8") if err != nil { fmt.Println("open mysql failed,", err) return } Db = db } func main() { rows, err := Db.Queryx("SELECT username,password,email FROM userinfo") if err != nil{ fmt.Println("Qeryx failed,error: ", err) return } for rows.Next() { //循环结果 var stu1 stu err = rows.StructScan(&stu1)// 转换为结构体 fmt.Println("stuct data:",stu1.Username,stu1.Password) } } //stuct data: wd 123 //stuct data: jack 1222
package main import ( _ "github.com/go-sql-driver/mysql" "github.com/jmoiron/sqlx" "fmt" ) var Db *sqlx.DB type stu struct { Username string `db:"username"` Password string `db:"password"` Department string `db:"department"` Email string `db:"email"` } func init() { db, err := sqlx.Open("mysql", "stu:1234qwer@tcp(10.0.0.241:3307)/test?charset=utf8") if err != nil { fmt.Println("open mysql failed,", err) return } Db = db } func main() { row := Db.QueryRow("SELECT username,password,email FROM userinfo where uid = ?",1) // QueryRow返回错误,错误通过Scan返回 var username,password,email string err :=row.Scan(&username,&password,&email) if err != nil{ fmt.Println(err) } fmt.Printf("this is QueryRow res:[%s:%s:%s]\n",username,password,email) var s stu err1 := Db.QueryRowx("SELECT username,password,email FROM userinfo where uid = ?",2).StructScan(&s) if err1 != nil{ fmt.Println("QueryRowx error :",err1) }else { fmt.Printf("this is QueryRowx res:%v",s) } } //this is QueryRow res:[wd:123:wd@163.com] //this is QueryRowx res:{jack 1222 jack@165.com}
package main import ( _ "github.com/go-sql-driver/mysql" "github.com/jmoiron/sqlx" "fmt" ) var Db *sqlx.DB type stu struct { Username string `db:"username"` Password string `db:"password"` Department string `db:"department"` Email string `db:"email"` } func init() { db, err := sqlx.Open("mysql", "stu:1234qwer@tcp(10.0.0.241:3307)/test?charset=utf8") if err != nil { fmt.Println("open mysql failed,", err) return } Db = db } func main() { var stus []stu err := Db.Select(&stus,"SELECT username,password,email FROM userinfo") if err != nil{ fmt.Println("Select error",err) } fmt.Printf("this is Select res:%v\n",stus) var s stu err1 := Db.Get(&s,"SELECT username,password,email FROM userinfo where uid = ?",2) if err1 != nil{ fmt.Println("GET error :",err1) }else { fmt.Printf("this is GET res:%v",s) } } //this is Select res:[{wd 123 wd@163.com} {jack 1222 jack@165.com}] //this is GET res:{jack 1222 jack@165.com}
tx, err := db.Begin() err = tx.Exec(...) err = tx.Commit() //或者使用sqlx扩展的事务 tx := db.MustBegin() tx.MustExec(...) err = tx.Commit()
为了维持一个持续的连接状态,Tx对象必须绑定和控制单个连接。在整个生命周期期间,一个Tx将保持连接,直到调用commit或Rollback()方法将其释放。必须非常谨慎地调用这些函数,否则连接将一直被占用,直到被垃圾回收。
使用示例:
package main import ( _ "github.com/go-sql-driver/mysql" "github.com/jmoiron/sqlx" "fmt" ) var Db *sqlx.DB func init() { db, err := sqlx.Open("mysql", "stu:1234qwer@tcp(10.0.0.241:3307)/test?charset=utf8") if err != nil { fmt.Println("open mysql failed,", err) return } Db = db } func main() { tx, err := Db.Beginx() _, err = tx.Exec("insert into userinfo(username,password) values(?,?)", "Rose","2223") if err != nil { tx.Rollback() } _, err = tx.Exec("insert into userinfo(username,password) values(?,?)", "Mick",222) if err != nil { fmt.Println("exec sql error:",err) tx.Rollback() } err = tx.Commit() if err != nil { fmt.Println("commit error") } }
连接池设置
当连接池中没有可用空闲连接时,连接池会自动创建连接,并且其增长是无限制的。最大连接数可以通过调用DB.SetMaxOpenConns来设置。未使用的连接标记为空闲,如果不需要则关闭。为了减少连接的开启和关闭次数,可以利用DB.SetMaxIdleConns方法来设定最大的空闲连接数。
注意:该设置方法golang版本至少为1.2
DB.SetMaxIdleConns(n int) 设置最大空闲连接数
DB.SetMaxOpenConns(n int) 设置最大打开的连接数
DB.SetConnMaxIdleTime(time.Second*10) 间隔时间
示例:
package main import ( _ "github.com/go-sql-driver/mysql" "github.com/jmoiron/sqlx" "fmt" ) var Db *sqlx.DB func init() { db, err := sqlx.Open("mysql", "stu:1234qwer@tcp(10.0.0.241:3307)/test?charset=utf8") if err != nil { fmt.Println("open mysql failed,", err) return } Db = db Db.SetMaxOpenConns(30) Db.SetMaxIdleConns(15) }
案例使用
var Db *sqlx.DB db, err := sqlx.Open("mysql","root:admin123@tcp(127.0.0.1:3306)/dududu?charset=utf8") Db = db rows, err := Db.Query("SELECT spu_id,title,price FROM dududu_shops") if err != nil{ fmt.Println("query failed,error: ", err) return } for rows.Next() { //循环结果 var spu_id,title,price string err = rows.Scan(&spu_id, &title, &price) println(spu_id,title,price) }
The above is the detailed content of How to connect golang to mysql database. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

MySQL's position in databases and programming is very important. It is an open source relational database management system that is widely used in various application scenarios. 1) MySQL provides efficient data storage, organization and retrieval functions, supporting Web, mobile and enterprise-level systems. 2) It uses a client-server architecture, supports multiple storage engines and index optimization. 3) Basic usages include creating tables and inserting data, and advanced usages involve multi-table JOINs and complex queries. 4) Frequently asked questions such as SQL syntax errors and performance issues can be debugged through the EXPLAIN command and slow query log. 5) Performance optimization methods include rational use of indexes, optimized query and use of caches. Best practices include using transactions and PreparedStatemen

Apache connects to a database requires the following steps: Install the database driver. Configure the web.xml file to create a connection pool. Create a JDBC data source and specify the connection settings. Use the JDBC API to access the database from Java code, including getting connections, creating statements, binding parameters, executing queries or updates, and processing results.

The process of starting MySQL in Docker consists of the following steps: Pull the MySQL image to create and start the container, set the root user password, and map the port verification connection Create the database and the user grants all permissions to the database

Installing MySQL on CentOS involves the following steps: Adding the appropriate MySQL yum source. Execute the yum install mysql-server command to install the MySQL server. Use the mysql_secure_installation command to make security settings, such as setting the root user password. Customize the MySQL configuration file as needed. Tune MySQL parameters and optimize databases for performance.

The main role of MySQL in web applications is to store and manage data. 1.MySQL efficiently processes user information, product catalogs, transaction records and other data. 2. Through SQL query, developers can extract information from the database to generate dynamic content. 3.MySQL works based on the client-server model to ensure acceptable query speed.

The key to installing MySQL elegantly is to add the official MySQL repository. The specific steps are as follows: Download the MySQL official GPG key to prevent phishing attacks. Add MySQL repository file: rpm -Uvh https://dev.mysql.com/get/mysql80-community-release-el7-3.noarch.rpm Update yum repository cache: yum update installation MySQL: yum install mysql-server startup MySQL service: systemctl start mysqld set up booting

Laravel is a PHP framework for easy building of web applications. It provides a range of powerful features including: Installation: Install the Laravel CLI globally with Composer and create applications in the project directory. Routing: Define the relationship between the URL and the handler in routes/web.php. View: Create a view in resources/views to render the application's interface. Database Integration: Provides out-of-the-box integration with databases such as MySQL and uses migration to create and modify tables. Model and Controller: The model represents the database entity and the controller processes HTTP requests.

C is more suitable for scenarios where direct control of hardware resources and high performance optimization is required, while Golang is more suitable for scenarios where rapid development and high concurrency processing are required. 1.C's advantage lies in its close to hardware characteristics and high optimization capabilities, which are suitable for high-performance needs such as game development. 2.Golang's advantage lies in its concise syntax and natural concurrency support, which is suitable for high concurrency service development.
