Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Use transactions for an sqlite query?

Tags:

sqlite

go

I'm working on an assignment that has us using transactions using sqlite. This is the part I'm struggling with:

open the database and start a transaction. Call the function to read in all the zones with that transaction, then commit the transaction when it returns

Since I'm only querying the database and not inserting/updating, I don't think I need to do much in terms of setting up the transaction. This is what I'm working with

database, _ := sql.Open("sqlite3", "./world.db")
tx, _ := database.Begin()
rows, err := database.Query("SELECT id, name FROM zones")
if err != nil {
    tx.Rollback()
} else {
    defer tx.Commit()
}

However, since the transaction tx isn't being used in the query I have no clue how to pass it to a function, so I'm thinking my query is set up wrong. I would think I'd need to use the transaction in the query somehow, maybe something like tx.Query(), but I'm at a loss at the moment.

like image 433
Grav Avatar asked May 12 '26 06:05

Grav


1 Answers

You can simply use tx.Query. Review https://golang.org/pkg/database/sql/#Tx.Query.

like image 105
Seaskyways Avatar answered May 14 '26 01:05

Seaskyways