How to Access an Open Database Connection from a Function in Golang?

Mary-Kate Olsen
Release: 2024-10-30 10:05:02
Original
140 people have browsed it

How to Access an Open Database Connection from a Function in Golang?

How to Refer to an Open Database Connection from a Function in Golang

In many Golang applications, it's necessary to interact with a database. Typically, the database connection is opened within the main function. However, when defining functions that require access to the database, you may encounter the issue of referring to the open database connection.

To resolve this issue, there are several approaches available:

Option 1: Global Database Connection

One solution is to declare the database connection as a global variable, making it accessible throughout the program, including within functions. This method is straightforward but may not be ideal for complex applications with multiple database connections.

Option 2: Function Parameter

Another option is to pass the database connection as a parameter to the function. This approach provides explicit control over which database connection is used and allows for the creation of functions that can work with different databases.

Option 3: Function Method

Alternatively, you can define the function as a method within a struct that holds the database connection. This technique offers a more object-oriented approach and ensures that the function always has access to the correct database connection.

Example Code:

Global Database Connection:

<code class="go">var db *sql.DB

func main() {
    db = sql.Open("sqlite3", "./house.db")
    room := Room{}
    err := addRoom(room)
    if err != nil {
        // Error handling
    }
}

func addRoom(room Room) error {
    stmt, err := db.Prepare("INSERT INTO Rooms (Name, Size, WindowCount, WallDecorationType, Floor) VALUES(?, ?, ?, ?, ?)")
    if err != nil {
        return err
    }

    _, err = stmt.Exec(room.Name, room.Size, room.WindowCount, room.WallDecorationType, room.Floor)
    return err
}</code>
Copy after login

Function Parameter:

<code class="go">func addRow(db *sql.DB, row Room) error {
    stmt, err := db.Prepare("INSERT INTO Rooms (Name, Size, WindowCount, WallDecorationType, Floor) VALUES(?, ?, ?, ?, ?)")
    if err != nil {
        return err
    }

    _, err = stmt.Exec(row.Name, row.Size, row.WindowCount, row.WallDecorationType, row.Floor)
    return err
}</code>
Copy after login

Function Method:

<code class="go">type dbConn struct {
    db *sql.DB
}

func (conn dbConn) addRow(row Room) error {
    stmt, err := conn.db.Prepare("INSERT INTO Rooms (Name, Size, WindowCount, WallDecorationType, Floor) VALUES(?, ?, ?, ?, ?)")
    if err != nil {
        return err
    }

    _, err = stmt.Exec(row.Name, row.Size, row.WindowCount, row.WallDecorationType, row.Floor)
    return err
}</code>
Copy after login

The best approach depends on the specific requirements of your application and the desired level of flexibility and control. These options provide various ways to access an open database connection from functions in a Golang program.

The above is the detailed content of How to Access an Open Database Connection from a Function 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
Latest Articles by Author
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!