Home >Backend Development >Golang >How to execute native SQL queries using Golang?

How to execute native SQL queries using Golang?

WBOY
WBOYOriginal
2024-06-01 10:00:58630browse

How to execute native SQL queries in Go: Import necessary packages (such as database/sql and database drivers). Open a database connection. Prepare SQL statements using the db.Prepare method. Use the stmt.Query method to perform queries, providing dynamic values. Use rows.Next and rows.Scan to iterate through the query results. Close the database connection to release resources.

如何使用 Golang 执行原生 SQL 查询?

#How to execute native SQL queries in Golang?

Golang provides a powerful SQL database package that allows you to interact with relational databases using native SQL queries. This tutorial will guide you on how to execute native SQL queries using Golang and provide a practical example.

Import the necessary packages

First, you need to import the necessary packages:

import (
    "database/sql"
    _ "github.com/go-sql-driver/mysql" // MySQL 驱动程序
)

Note: Different databases will require their own drivers . See [godoc](https://godoc.org/database/sql/driver) for a list of supported drivers.

Open a database connection

Next, open a database connection:

db, err := sql.Open("mysql", "user:password@tcp(host:port)/database")
if err != nil {
    log.Fatal(err)
}

Make sure to add user, password Replace , host, port and database with the corresponding values.

Preparing SQL Statements

To prepare a SQL query, use the Prepare method:

stmt, err := db.Prepare("SELECT * FROM users WHERE name = ?")
if err != nil {
    log.Fatal(err)
}

This will create a precompiled SQL statement for later execution. ?Placeholder represents a dynamic value that will be replaced during execution.

Execute SQL Query

To execute a query using a specified dynamic value, use the Query method:

rows, err := stmt.Query("John")
if err != nil {
    log.Fatal(err)
}

This will Returns a Rows object containing the query results.

Processing query results

To traverse the query results, please use the Scan method:

for rows.Next() {
    var id int
    var name string
    if err := rows.Scan(&id, &name); err != nil {
        log.Fatal(err)
    }
    fmt.Printf("ID: %d, Name: %s\n", id, name)
}

Close the database connection

Finally, close the database connection to release resources:

db.Close()

Practical case

The following is a practical case to demonstrate how to add data to the database Insert a record and get it:

package main

import (
    "database/sql"
    "fmt"

    _ "github.com/go-sql-driver/mysql" // MySQL 驱动程序
)

func main() {
    db, err := sql.Open("mysql", "user:password@tcp(host:port)/database")
    if err != nil {
        log.Fatal(err)
    }
    defer db.Close()

    stmt, err := db.Prepare("INSERT INTO users (name) VALUES (?)")
    if err != nil {
        log.Fatal(err)
    }

    _, err = stmt.Exec("Jane")
    if err != nil {
        log.Fatal(err)
    }

    stmt, err = db.Prepare("SELECT * FROM users WHERE name = ?")
    if err != nil {
        log.Fatal(err)
    }

    rows, err := stmt.Query("Jane")
    if err != nil {
        log.Fatal(err)
    }

    for rows.Next() {
        var id int
        var name string
        if err := rows.Scan(&id, &name); err != nil {
            log.Fatal(err)
        }
        fmt.Printf("ID: %d, Name: %s\n", id, name)
    }
}

The above is the detailed content of How to execute native SQL queries using Golang?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
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