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>
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>
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:
<code class="go">func addRow(db *sql.DB, row Room) error</code>
<code class="go">type dbConn struct { db *sql.DB } func (conn dbConn) addRow(row Room) error</code>
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>
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!