How to do MySQL operation details in Golang

  • 2020-07-21 08:24:07
  • OfStack

preface

Golang does not officially provide a database driver, but the standard interface for implementing the driver is provided through the database/sql/driver package. Many open source drivers can be found on Github.

go-sql-driver /mysql is one of the more recommended drivers, which fully supports the database/sql interface.

Using this drive, import in project:


import (
 "database/sql"
 _ "github.com/go-sql-driver/mysql"
)

Before using the database/sql package, it is important to understand that sql.DB does not represent a database connection, does not establish any connection with the database, and does not verify the validity of parameters. To know the validity of DSN, you need to use the sql.DB instance (such as db) db.Ping () method, as follows:


err = db.Ping()
if err != nil {
 //  Error handling 
}

One instance of ES39en.DB is obtained using the sql.Open () method. It should be noted that ES41en. DB is designed to be used as a long connection. Open() and Close() should not be frequently used in projects. Open() is used only once until the end of the program task.

Once you have the instance of ES50en.DB, you are ready to manipulate the database.

When working with databases, the recommended practice is to precompile SQL statements using ES55en.Prepare () for high security and to a certain extent to avoid attacks such as SQL injection.

1 Some examples:


/*
  Query operation 
*/
stmt, err := db.Prepare("SELECT `user_name` FROM `users` WHERE `id` = ?")
defer stmt.Close()
if err != nil {
 // Error handling 
}
var userName string
//Scan()  Copy the results to userName
err = stmt.QueryRow(1).Scan(&userName)

fmt.Println(userName)

/*
  Multi-row result 
*/
stmt, err := db.Prepare("SELECT `user_name` FROM `users` WHERE `age` = ?")
defer stmt.Close()
if err != nil {
 // Error handling 
}

rows, err := stmt.Query( age )
if err != nil {
 // Error handling 
}

for rows.Next() {
 var userName string
 if err := rows.Scan(&userName); err != nil {
  // Error handling 
 }
}

/*
  The insert 
*/
stmt, err := db.Prepare("INSERT INTO `users` (`user_name`, `age`) VALUES(?, ?)")
defer stmt.Close()
if err != nil {
 // Error handling 
}
stmt.Exec(" The name " Age, )

/*
  The transaction 
*/
tx, err := db.Begin()
if err != nil {
 // Error handling 
}
defer tx.Rollback()

stmt, err := db.Prepare("")
defer stmt.Close()
if err != nil {
 // Error handling 
}

stmt.Exec()
err = tx.Commit()
if err != nil {
 // Error handling 
}

conclusion


Related articles: