dongtang3155 2017-03-03 14:40
浏览 30
已采纳

在函数内部引用开放式数据库连接-Golang

My main function opens a database connection:

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

    ...
}

Then, I want to create a function that allows me to add a row to the database based on a passed struct:

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
}

But obviously I can't do that because the addRow() function has no idea what db is.

How would I make this function work? Should I perhaps, open the database outside of the main function?

  • 写回答

1条回答 默认 最新

  • dongseshu0698 2017-03-03 14:50
    关注

    Depending on how your application works, you can either

    1. keep the db global
    2. pass db as a parameter
    3. make addRoom a method

    What I typically do for API services is create a global db, like this:

    var db *sql.DB
    
    func main() {
        var err error
        db, err = sql.Open("sqlite3", "./house.db")
        checkErr(err)
        // create room Room{}
        err = addRoom(room)
        checkErr(err)
    }
    

    But you can also pass db as a parameter:

    func addRow(db *sql.DB, row Room) error
    

    Or you can create a struct which keeps the connection as an attribute and makes addRow a method:

    type dbConn struct {
        db *sql.DB
    }
    
    func (conn dbConn) addRow(row Room) error
    

    This book has some nice examples.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 kylin启动报错log4j类冲突
  • ¥15 超声波模块测距控制点灯,灯的闪烁很不稳定,经过调试发现测的距离偏大
  • ¥15 import arcpy出现importing _arcgisscripting 找不到相关程序
  • ¥15 onvif+openssl,vs2022编译openssl64
  • ¥15 iOS 自定义输入法-第三方输入法
  • ¥15 很想要一个很好的答案或提示
  • ¥15 扫描项目中发现AndroidOS.Agent、Android/SmsThief.LI!tr
  • ¥15 怀疑手机被监控,请问怎么解决和防止
  • ¥15 Qt下使用tcp获取数据的详细操作
  • ¥15 idea右下角设置编码是灰色的