Home > Backend Development > Golang > How to Access a Database Connection from a Function in Go?

How to Access a Database Connection from a Function in Go?

Patricia Arquette
Release: 2024-10-29 12:01:29
Original
754 people have browsed it

How to Access a Database Connection from a Function in Go?

Referencing an Open Database Connection within a Function in Go

When working with databases in Go, it's common to establish a connection to the database in the main function and then utilize this connection throughout the application. However, what happens when you want to encapsulate database operations within a function?

Consider the following scenario. In your main function, you open a database connection:

<code class="go">func main() {
    db, err := sql.Open("sqlite3", "./house.db")
    checkErr(err)

    ...
}</code>
Copy after login

Now, you're interested in creating a function that adds rows to the database based on a passed struct:

<code class="go">func addRow(row Room) error {
    stmt, err := db.Prepare("INSERT INTO Rooms (Name, Size, WindowCount, WallDecorationType, Floor) VALUES(?, ?, ?, ?, ?)")
    _, err = stmt.Exec(row.Name , row.Size , row.WindowCount , row.WallDecorationType , row.Floor)
    return err
}</code>
Copy after login

But here lies the challenge: the addRow() function has no knowledge of the db variable defined in the main function.

How to Handle Database Connection References

Depending on the nature of your application, you have several options to reference the database connection within the addRow() function:

  • Global Variable: Declare db as a global variable. This means it will be accessible anywhere in your program, including the addRow() function. Note that using global variables should be used sparingly.
  • Function Parameter: Pass the db connection as a parameter to the addRow() function. This provides more explicit control over the connection, and it allows you to use different database connections if needed.
<code class="go">func addRow(db *sql.DB, row Room) error</code>
Copy after login
  • Method: Create a struct that manages the database connection and make addRow() a method on that struct. This approach encapsulates the database connection within the struct.
<code class="go">type dbConn struct {
    db *sql.DB
}

func (conn dbConn) addRow(row Room) error</code>
Copy after login

Example Usage

Let's demonstrate the usage of the global variable approach:

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

func main() {
    db, err := sql.Open("sqlite3", "./house.db")
    checkErr(err)

    // create room Room{}
    err = addRow(room)
    checkErr(err)
}</code>
Copy after login

By declaring db as a global variable, it becomes accessible to the addRow() function anywhere in the program.

Keep in mind that the approach you choose should be tailored to the specific requirements of your application, its architecture, and performance considerations.

The above is the detailed content of How to Access a Database Connection from a Function in Go?. For more information, please follow other related articles on the PHP Chinese website!

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