简易的学生管理系统(go语言)
首先,你需要安装github.com/go-sql-driver/mysql
这个包来操作MySQL数据库。你可以使用以下命令来安装它:
go get github.com/go-sql-driver/mysql
package main
import (
"database/sql"
"fmt"
"os"
"bufio"
"strings"
_ "github.com/go-sql-driver/mysql" // 导入MySQL数据库驱动
)
type Student struct {
ID int
Name string
Age int
Grade float64
}
var db *sql.DB
func init() {
var err error
// 创建数据库连接字符串
dsn := "username:password@tcp(localhost:3306)/dbname"
// 打开MySQL数据库连接
db, err = sql.Open("mysql", dsn)
if err != nil {
fmt.Println("数据库连接失败:", err)
os.Exit(1)
}
// 测试数据库连接
err = db.Ping()
if err != nil {
fmt.Println("数据库连接失败:", err)
os.Exit(1)
}
// 创建表格(如果不存在)
_, err = db.Exec(`
CREATE TABLE IF NOT EXISTS students (
id INT AUTO_INCREMENT PRIMARY KEY,
name VARCHAR(255),
age INT,
grade FLOAT
)
`)
if err != nil {
fmt.Println("创建表格失败:", err)
os.Exit(1)
}
}
func addStudent(name string, age int, grade float64) {
// 向数据库插入学生信息
_, err := db.Exec("INSERT INTO students (name, age, grade) VALUES (?, ?, ?)", name, age, grade)
if err != nil {
fmt.Println("添加学生信息失败:", err)
return
}
fmt.Println("学生信息已添加")
}
func getStudent(name string) (Student, error) {
var student Student
// 查询学生信息
row := db.QueryRow("SELECT id, name, age, grade FROM students WHERE name = ?", name)
err := row.Scan(&student.ID, &student.Name, &student.Age, &student.Grade)
return student, err
}
func listStudents() {
rows, err := db.Query("SELECT id, name, age, grade FROM students")
if err != nil {
fmt.Println("查询学生信息失败:", err)
return
}
defer rows.Close()
fmt.Println("所有学生信息:")
for rows.Next() {
var student Student
err := rows.Scan(&student.ID, &student.Name, &student.Age, &student.Grade)
if err != nil {
fmt.Println("读取学生信息失败:", err)
return
}
fmt.Printf("ID: %d, 姓名: %s, 年龄: %d, 成绩: %.2f\n", student.ID, student.Name, student.Age, student.Grade)
}
}
func main() {
fmt.Println("欢迎使用学生管理系统!")
fmt.Println("可用命令:add, get, list, exit")
scanner := bufio.NewScanner(os.Stdin)
for {
fmt.Print("请输入命令:")
scanner.Scan()
command := scanner.Text()
switch command {
case "add":
fmt.Print("请输入学生姓名:")
scanner.Scan()
name := scanner.Text()
fmt.Print("请输入学生年龄:")
scanner.Scan()
age := 0
fmt.Sscanf(scanner.Text(), "%d", &age)
fmt.Print("请输入学生成绩:")
scanner.Scan()
grade := 0.0
fmt.Sscanf(scanner.Text(), "%f", &grade)
addStudent(name, age, grade)
case "get":
fmt.Print("请输入学生姓名:")
scanner.Scan()
name := scanner.Text()
student, err := getStudent(name)
if err == sql.ErrNoRows {
fmt.Println("未找到该学生的信息。")
} else if err != nil {
fmt.Println("查询学生信息失败:", err)
} else {
fmt.Printf("ID: %d, 姓名: %s, 年龄: %d, 成绩: %.2f\n", student.ID, student.Name, student.Age, student.Grade)
}
case "list":
listStudents()
case "exit":
fmt.Println("感谢使用学生管理系统!")
db.Close()
return
default:
fmt.Println("无效的命令,请重新输入。")
}
}
}
标签:Println,name,err,管理系统,fmt,简易,student,go,scanner
From: https://www.cnblogs.com/xdtxblog/p/17617862.html