package main
import (
"database/sql"
"fmt"
_ "github.com/mattn/go-sqlite3"
"log"
"time"
)
/**
id int primary key not null,
name text not null,
age int not null,
address char(50),
salary real
*/
type User struct {
id int
name string
age int
address int
salary float32
}
func main() {
db, err := sql.Open("sqlite3", "D:\\sqlite-tools-win32-x64-202310241106\\test_db.db")
if err != nil {
log.Fatal(err)
}
defer db.Close()
err = db.Ping()
if err != nil {
log.Fatal("数据库连接失败!!!:", err)
}
fmt.Println("数据库连接成功")
// 查询用户
// 获取开始时间
startTime := time.Now()
users := queryUsers(db)
fmt.Println("Users:")
for _, user := range users {
fmt.Printf("id: %d, name: %s, address: %d,age: %d,salary: %.2f \n ", user.id, user.name, user.address, user.age, user.salary)
}
endTime := time.Now()
fmt.Println("运行时间:", endTime.Sub(startTime).Seconds())
}
func queryUsers(db *sql.DB) []User {
rows, err := db.Query("select * from user limit 1000")
if err != nil {
log.Fatal(err)
}
var users []User
for rows.Next() {
var user User
err := rows.Scan(&user.id, &user.name, &user.age, &user.address, &user.salary)
if err != nil {
log.Fatal(err)
}
users = append(users, user)
}
return users
}
func updateUser(db *sql.DB, user User) {
sqlStmt := `
UPDATE users SET name = ? WHERE id = ?;
`
_, err := db.Exec(sqlStmt, user.Name, user.ID)
if err != nil {
log.Fatal(err)
}
fmt.Println("User updated successfully!")
}
func deleteUser(db *sql.DB, userID int) {
sqlStmt := `
DELETE FROM users WHERE id = ?;
`
_, err := db.Exec(sqlStmt, userID)
if err != nil {
log.Fatal(err)
}
fmt.Println("User deleted successfully!")
}
func insertUser(db *sql.DB, user User) {
sqlStmt := `
INSERT INTO users (name, email) VALUES (?, ?);
`
_, err := db.Exec(sqlStmt, user.Name, user.Email)
if err != nil {
log.Fatal(err)
}
fmt.Println("User inserted successfully!")
}
标签:log,users,err,CRUD,db,user,简单,go,User
From: https://www.cnblogs.com/MnysLjj/p/17798461.html