How to connect to the database in golang?

PHPz
Release: 2023-04-25 15:47:32
Original
2255 people have browsed it

In modern application development, interacting with the database is a very important task, because most application data is stored in the database. In the development of Golang, connecting to the database is also an essential task. This article will introduce how to use Golang to connect to the database.

  1. Install the database driver

Connecting to the database in Golang requires the use of the corresponding database driver. Therefore, before starting, we need to install the corresponding driver. Golang can connect to many types of databases, such as MySQL, PostgreSQL, SQL Server, Oracle, etc. Each database requires a different driver.

We will take MySQL as an example to explain how to connect to the database. Before connecting to MySQL, we need to install the mysql driver. You can use the following command to install it:

go get -u github.com/go-sql-driver/mysql
Copy after login

Of course, you also need to import the corresponding library in the code.

import (
  "database/sql"
  _ "github.com/go-sql-driver/mysql"
)
Copy after login
  1. Connecting to MySQL

Connecting to MySQL requires the following basic information:

  • Database name
  • Host name/IP address
  • Port number
  • Username
  • Password

In Golang, you can use the following code to connect to MySQL:

func Connect() (*sql.DB, error){

  //设置数据库连接信息
  db, err := sql.Open("mysql", "USER_NAME:PASSWORD@tcp(HOST:PORT)/DB_NAME")

  //测试连接
  err = db.Ping()
  if err != nil {
    return nil, err
  }

  return db, nil
}
Copy after login

In this code snippet, we use the sql.Open() function to open a database connection and specify the database connection information by passing parameters. In this case, HOST is the IP address or hostname of the database host, PORT is the port number for MySQL, DB_NAME is the name of the database to connect to, and USER_NAME and PASSWORD are the username and password for the database. If the connection is successful, a pointer to the database instance is returned.

  1. Execute queries

After connecting to the database, we can perform various queries and operations. In Golang, you can use the Prepare() and Exec() or Query() functions to execute SQL queries.

For example, the following code snippet can execute an Insert query:

func AddProduct(name string, price int) error {

  //连接到数据库
  db, err := Connect()
  if err != nil {
    return err
  }
  defer db.Close()

  //准备SQL语句
  stmt, err := db.Prepare("INSERT INTO products(name, price) VALUES(?,?)")
  if err != nil {
    return err
  }
  defer stmt.Close()

  //执行查询
  _, err = stmt.Exec(name, price)
  if err != nil {
    return err
  }

  return nil
}
Copy after login

In this code, we use the Prepare() function to prepare a SQL statement and then use Exec()The function executes the query. Exec()The function returns the number of rows and error information. If the error is empty, the insert statement succeeds.

Similarly, we can use the Query() and Scan() functions to execute Select queries and obtain query result sets.

  1. Conclusion

In this article, we learned how to connect to MySQL database using Golang. Connecting to the database requires installing the corresponding driver and specifying connection information. Once the connection is successful, we can perform various SQL queries and operations, including Insert, Update, Delete, and Select. I wish you success.

The above is the detailed content of How to connect to the database in golang?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!