学生成绩管理系统c#代码
时间: 2024-08-12 14:08:34 浏览: 29
创建一个简单的学生成绩管理系统用C#可以涉及多个步骤,包括设计数据库、用户界面、以及处理业务逻辑。以下是一个简化的示例,展示了如何使用ADO.NET连接数据库和基本的增删改查操作:
```csharp
using System;
using System.Data.SqlClient;
public class Student
{
public int ID { get; set; }
public string Name { get; set; }
public double GPA { get; set; }
}
// 数据库连接字符串
string connectionString = "Data Source=your_server;Initial Catalog=your_database;Integrated Security=True;";
// 连接数据库
SqlConnection connection = new SqlConnection(connectionString);
public void AddStudent(Student student)
{
string query = "INSERT INTO Students (Name, GPA) VALUES (@Name, @GPA)";
SqlCommand command = new SqlCommand(query, connection);
command.Parameters.AddWithValue("@Name", student.Name);
command.Parameters.AddWithValue("@GPA", student.GPA);
connection.Open();
command.ExecuteNonQuery();
}
public void UpdateStudent(int id, Student updatedStudent)
{
string query = "UPDATE Students SET Name = @Name, GPA = @GPA WHERE ID = @ID";
SqlCommand command = new SqlCommand(query, connection);
command.Parameters.AddWithValue("@ID", id);
command.Parameters.AddWithValue("@Name", updatedStudent.Name);
command.Parameters.AddWithValue("@GPA", updatedStudent.GPA);
command.ExecuteNonQuery();
}
public Student GetStudent(int id)
{
string query = "SELECT * FROM Students WHERE ID = @ID";
SqlCommand command = new SqlCommand(query, connection);
command.Parameters.AddWithValue("@ID", id);
connection.Open();
var reader = command.ExecuteReader();
if (reader.Read())
{
Student student = new Student { ID = reader.GetInt32(0), Name = reader.GetString(1), GPA = reader.GetDouble(2) };
return student;
}
return null;
}
// 关闭连接
public void CloseConnection()
{
connection.Close();
}
// 示例用法
public static void Main(string[] args)
{
// 初始化并添加学生
var system = new StudentManagementSystem();
Student student = new Student { Name = "Alice", GPA = 3.5 };
system.AddStudent(student);
// 更新学生信息
student.Name = "Alice Smith";
system.UpdateStudent(student.ID, student);
// 查询学生
Student retrievedStudent = system.GetStudent(student.ID);
Console.WriteLine($"Retrieved student: {retrievedStudent.Name} - GPA: {retrievedStudent.GPA}");
}
```