How to connect to remote database using Golang?

WBOY
Release: 2024-06-01 20:31:59
Original
886 people have browsed it

Through the Go standard library database/sql package, you can connect to remote databases such as MySQL, PostgreSQL or SQLite: Create a connection string containing database connection information. Use the sql.Open() function to open a database connection. Perform database operations such as SQL queries and insert operations. Use defer to close the database connection to release resources.

如何用 Golang 连接远程数据库?

How to connect to a remote database using Golang

Golang is a powerful programming language that can easily connect to a remote database. This tutorial will introduce how to use the Go standard library database/sql package to connect to remote databases such as MySQL, PostgreSQL and SQLite.

Requirements

  • Golang 1.16 or higher
  • Remote database (such as MySQL, PostgreSQL or SQLite)

Connection String

First we need to create a connection string that contains the information needed to connect to the database. Here's how to create connection strings for different databases:

MySQL:

"user:password@tcp(host:port)/dbname"
Copy after login

PostgreSQL:

"user=username password=password host=address port=port dbname=database"
Copy after login

SQLite:

"path/to/sqlite.db"
Copy after login

Among them, user, password, host, port and dbname is database specific.

Connect to the database

Use the database/sql package to connect to the database:

import (
    "database/sql"
    _ "github.com/go-sql-driver/mysql" // Import MySQL driver
    _ "github.com/lib/pq" // Import PostgreSQL driver
    _ "github.com/mattn/go-sqlite3" // Import SQLite driver
)

func main() {
    // Create a connection string
    connStr := "user:password@tcp(host:port)/dbname"

    // Open the database connection
    db, err := sql.Open("mysql", connStr)
    if err != nil {
        panic(err)
    }
    defer db.Close()  // Close the connection when the function returns
}
Copy after login

Practical case

The following is a database using MySQL Simple example of:

package main

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

func main() {
    // Connect to the database
    db, err := sql.Open("mysql", "root:@/test")
    if err != nil {
        panic(err)
    }
    defer db.Close() // Close the connection when the function returns

    // Create a table
    query := `CREATE TABLE IF NOT EXISTS users (
        id INT PRIMARY KEY AUTO_INCREMENT,
        username VARCHAR(255) NOT NULL,
        password VARCHAR(255) NOT NULL
    );`
    _, err = db.Exec(query)
    if err != nil {
        panic(err)
    }

    // Insert a record into the table
    query = `INSERT INTO users (username, password) VALUES (?, ?)`
    stmt, err := db.Prepare(query)
    if err != nil {
        panic(err)
    }
    _, err = stmt.Exec("admin", "password")
    if err != nil {
        panic(err)
    }

    // Retrieve the record from the table
    query = `SELECT * FROM users WHERE id = ?`
    var id int
    var username string
    var password string
    err = db.QueryRow(query, 1).Scan(&id, &username, &password)
    if err != nil {
        panic(err)
    }
    fmt.Println("ID:", id, "Username:", username, "Password:", password)
}
Copy after login

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

Related labels:
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!