从数据库中读取数据
在http://sqlitebrowser.org/下载sqlite3可视化工具,在本main.go同目录下创建personal.db
数据库,创建表如下:
package main
import (
"database/sql"
"fmt"
_ "github.com/mattn/go-sqlite3"
)
// 用struct类型将来自SQL数据库的数据映射到内存中的对象
type Profile struct {
ProfileId int
FirstName string
LastName string
Age int
}
func main() {
db, err := sql.Open("sqlite3", "./personal.db")
checkError(err)
var profile Profile
// Query可以使用参数
rows, err := db.Query("select ProfileId, FirstName, LastName, Age from Profile where FirstName = ? and LastName = ?", "Tarik", "Guney")
checkError(err)
for rows.Next() {
err := rows.Scan(&profile.ProfileId, &profile.FirstName, &profile.LastName, &profile.Age)
checkError(err)
fmt.Println(profile)
}
rows.Close()
db.Close()
}
func checkError(err error) {
if err != nil {
panic(err)
}
}
将数据插入数据库
package main
import (
_ "github.com/mattn/go-sqlite3"
"database/sql"
"fmt"
)
type Profile struct{
ProfileId int
FirstName string
LastName string
Age int
}
func main(){
db, err := sql.Open("sqlite3", "./personal.db")
checkError(err)
/* 更新数据库数据
statement, err := db.Prepare("update Profile set FirstName = ? where ProfileId = ?")
checkError(err)
statement.Exec("Martha", 5)
*/
statement, err := db.Prepare("insert into Profile (FirstName, LastName, Age) values(?,?,?)")
checkError(err)
statement.Exec("Jessica", "McArthur", 30)
/* 删除数据库数据
statement ,err := db.Prepare("delete from Profile where ProfileId = ?")
checkError(err)
statement.Exec(3)
*/
var profile Profile
rows, err := db.Query("select ProfileId, FirstName, LastName, Age from Profile")
checkError(err)
for rows.Next(){
err := rows.Scan(&profile.ProfileId, &profile.FirstName, &profile.LastName, &profile.Age)
checkError(err)
fmt.Println(profile)
}
rows.Close()
db.Close()
}
func checkError(err error) {
if (err != nil) {
panic(err)
}
}