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() {
db, err := sql.Open( "mysql" , "root:passwd@tcp(0.0.0.0:3306)/user" )
if err != nil {
panic(err)
}
err = db.Ping()
if err != nil {
panic(err)
}
fmt.Print( "Pong\n" )
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() {
db, err := sql.Open( "mysql" , "root:passwd@tcp(0.0.0.0:3306)/user" )
if err != nil {
panic(err)
}
_, err = db.Exec("CREATE TABLE user(id INT NOT NULL, name VARCHAR( 20 ),
PRIMARY KEY (ID));")
if err != nil {
panic(err)
}
fmt.Print( "Successfully Created\n" )
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() {
db, err := sql.Open( "mysql" , "root:passwd@tcp(0.0.0.0:3306)/user" )
if err != nil {
panic(err)
}
_, err = db.Query( "INSERT INTO user VALUES(1,'sam')" )
if err != nil {
panic(err)
}
fmt.Print( "Successfully Inserted\n" )
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() {
db, err := sql.Open( "mysql" , "root:passwd@tcp(0.0.0.0:3306)/user" )
if err != nil {
panic(err)
}
result, err := db.Query( "SELECT * FROM user" )
if err != nil {
panic(err)
}
for result.Next() {
var id int
var name string
err = result.Scan(&id, &name)
if err != nil {
panic(err)
}
fmt.Printf( "Id: %d Name: %s\n" , id, name)
}
defer db.Close()
}
|
Output:
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...