How to Use Go with MySQL?
Last Updated :
04 Sep, 2021
MySQL is an open-source relational database management system based on Structured Query Language(SQL). It is a relational database that organizes data into one or more tables in which data are related to each other.
Database Driver: A Database Driver implements a protocol for a database connection. The Driver is like an adapter that connects to a generic interface to a specific database.
Initial Setup:
Start MySQL server and install go MySQL driver with the following command.
go get -u github.com/go-sql-driver/mysql
Creating database object:
Create a database object with sql.Open. There no connection established with MySQL instead, it creates only a database object which can be used later.
db, err := sql.Open("mysql", "<user>:<password>@tcp(127.0.0.1:3306)/<database-name>")
Replace 3306 if not using MySQL on the default port.
Go
package main
import (
"database/sql"
"fmt"
_ "github.com/go-sql-driver/mysql"
)
func main() {
// create a database object which can be used
// to connect with database.
db, err := sql.Open("mysql", "root:passwd@tcp(0.0.0.0:3306)/user")
// handle error, if any.
if err != nil {
panic(err)
}
// Now its time to connect with oru database,
// database object has a method Ping.
// Ping returns error, if unable connect to database.
err = db.Ping()
// handle error
if err != nil {
panic(err)
}
fmt.Print("Pong\n")
// database object has a method Close,
// which is used to free the resource.
// Free the resource when the function
// is returned.
defer db.Close()
}
Output:
fig 1.1
Execute Database Query: A database query can be done with Exec() and Query().
1. Creating a Database Table with SQL query and Exec().
Go
package main
import (
"database/sql"
"fmt"
_ "github.com/go-sql-driver/mysql"
)
func main() {
// create a database object which can be used
// to connect with database.
db, err := sql.Open("mysql", "root:passwd@tcp(0.0.0.0:3306)/user")
// handle error, if any.
if err != nil {
panic(err)
}
// database object has a method called Exec,
// it executes a database query, but it does
// not return any row as result.
// Here we create a database table with a SQL query.
_, err = db.Exec("CREATE TABLE user(id INT NOT NULL, name VARCHAR(20),
PRIMARY KEY (ID));")
// handle error
if err != nil {
panic(err)
}
fmt.Print("Successfully Created\n")
// database object has a method Close,
// which is used to free the resource.
// Free the resource when the function
// is returned.
defer db.Close()
}
Output:
2. Inserting a row into Database Table with SQL query in Query().
Go
package main
import (
"database/sql"
"fmt"
_ "github.com/go-sql-driver/mysql"
)
func main() {
// create a database object which can be used
// to connect with database.
db, err := sql.Open("mysql", "root:passwd@tcp(0.0.0.0:3306)/user")
// handle error, if any.
if err != nil {
panic(err)
}
// database object has a method called Query,
// It can execute a SQL query and return rows
// as result. Here we insert a row into the table,
// no row returned as result for this operation.
_, err = db.Query("INSERT INTO user VALUES(1,'sam')")
// handle error
if err != nil {
panic(err)
}
fmt.Print("Successfully Inserted\n")
// database object has a method Close,
// which is used to free the resource.
// Free the resource when the function
// is returned.
defer db.Close()
}
Output:
3. Using SQL query in Query() to return all rows from the user table.
Go
package main
import (
"database/sql"
"fmt"
_ "github.com/go-sql-driver/mysql"
)
func main() {
// create a database object which can be
// used to connect with database.
db, err := sql.Open("mysql", "root:passwd@tcp(0.0.0.0:3306)/user")
// handle error, if any.
if err != nil {
panic(err)
}
// Here a SQL query is used to return all
// the data from the table user.
result, err := db.Query("SELECT * FROM user")
// handle error
if err != nil {
panic(err)
}
// the result object has a method called Next,
// which is used to iterate through all returned rows.
for result.Next() {
var id int
var name string
// The result object provided Scan method
// to read row data, Scan returns error,
// if any. Here we read id and name returned.
err = result.Scan(&id, &name)
// handle error
if err != nil {
panic(err)
}
fmt.Printf("Id: %d Name: %s\n", id, name)
}
// database object has a method Close,
// which is used to free the resource.
// Free the resource when the function
// is returned.
defer db.Close()
}
Output:
Similar Reads
How to Use Go With MongoDB? MongoDB is an open-source NoSQL database. It is a document-oriented database that uses a JSON-like structure called BSON to store documents like key-value pairs. MongoDB provides the concept of collection to group documents. In this article, we will learn about How to Use Go With MongoDB by understa
15+ min read
Setting Up Gorm With MySQL In this article, weâll set up GORM, an ORM library, with MySQL using the Gin web framework in Go. GORM provides features that make database interactions easier by allowing the use of Go structs instead of raw SQL queries, which helps reduce boilerplate code and keeps the codebase cleaner.Weâll take
6 min read
How to use C++ in Go Go (Golang) is known for its simplicity, efficiency, and concurrency model, while C++ offers high performance and control over system resources. There are cases where you might want/need to use the simpler interface of Go but with the performance of C++, for instance, when you have legacy C++ librar
3 min read
How to Use Connection Pooling with MySQL in Node.js? MySQL is one of the most preferred relational databases, While Node.js is another name for JavaScript runtime environment. While assessing a large number of connections in the database in a Node. In this regard, effectiveness in managing them is also a significant determinant when developing and mai
3 min read
How to Install Go on Windows? Prerequisite: Introduction to Go Programming Language Before, we start with the process of Installing Golang on our System. We must have first-hand knowledge of What the Go Language is and what it actually does? Go is an open-source and statically typed programming language developed in 2007 by Robe
3 min read