This is a creation in Article, where the information may have evolved or changed.
Use SQLite database in Go language
1. Drive
Go support SQLite driver is also more, but many are not support Database/sql interface
- Https://github.com/mattn/go-sqlite3 supports DATABASE/SQL interfaces, based on CGO (see the official documentation or the chapters later in this book for information on CGO)
- Https://github.com/feyeleanor/gosqlite3 does not support Database/sql interface, based on CGO write
- Https://github.com/phf/go-sqlite3 does not support Database/sql interface, based on CGO write
Currently support Database/sql's SQLite database driver only the first one, I am currently using it to develop projects. The use of standard interfaces facilitates future migration when better drivers are present.
2. Instance Code
The database table structure for the example is as follows, and the corresponding SQL is built for the table:
CREATE TABLE' userinfo ' (' uid ' )INTEGER PRIMARY KEYAutoIncrement, ' username 'VARCHAR( -)NULL, ' Departname 'VARCHAR( -)NULL, ' created ' DATENULL);CREATE TABLE' userdeatail ' (' uid ' )INT(Ten)NULL, ' intro 'TEXT NULL, ' profile 'TEXT NULL, PRIMARY KEY(' uid '));
Look at the following go program is how to manipulate database table data: additions and deletions
Package Mainimport ("Database/sql" "FMT" _ "Github.com/mattn/go-sqlite3") Func main () {db, err:= SQL. Open ("Sqlite3","./foo.db") Checkerr (err)//Inserting Datastmt, err: = db. Prepare ("INSERT into UserInfo (username, departname, created) VALUES (?,?,?)") Checkerr (ERR) res, err:= stmt. Exec ("Astaxie","Research and Development Department","2012-12-09") Checkerr (err)ID, Err: =Res. Lastinsertid () Checkerr (err) fmt. Println (ID) //Update Datastmt, err = db. Prepare ("update userinfo set username=? where uid=?") Checkerr (ERR) res, err= stmt. Exec ("astaxieupdate",ID) Checkerr (err) affect, err:=Res. Rowsaffected () Checkerr (err) fmt. PRINTLN (Affect)//Querying DataRows, err: = db. Query ("SELECT * from UserInfo") Checkerr (err) forrows. Next () {var uidintvar usernamestringVar Departmentstringvar createdstringErr= Rows. Scan (&uid, &username, &department, &created) Checkerr (err) fmt. PRINTLN (UID) fmt. PRINTLN (username) fmt. PRINTLN (department) FMT. Println (created)}//Delete Datastmt, err = db. Prepare ("Delete from userinfo where uid=?") Checkerr (ERR) res, err= stmt. Exec (ID) Checkerr (err) affect, err=Res. Rowsaffected () Checkerr (err) fmt. PRINTLN (affect) db. Close ()}func Checkerr (err error) {ifErr! =Nil {panic (err)}}
We can see that the code above is almost exactly the same as the code in the MySQL example, and the only change is that the imported driver is changed, and then the call sql.Open
is opened in SQLite mode.