C#基于数据库和控制台的学生选课系统代码
时间: 2023-08-23 12:06:07 浏览: 56
好的,下面是一个简单的基于控制台和数据库的学生选课系统的代码示例,供你参考:
```
using System;
using System.Collections.Generic;
using System.Data.SqlClient;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ConsoleApp1
{
class Program
{
static void Main(string[] args)
{
// 连接字符串
string connStr = "Data Source=(localdb)\\MSSQLLocalDB;Initial Catalog=CourseSystemDB;Integrated Security=True;Connect Timeout=30;Encrypt=False;TrustServerCertificate=False;ApplicationIntent=ReadWrite;MultiSubnetFailover=False";
// 创建 SqlConnection 对象
SqlConnection conn = new SqlConnection(connStr);
// 打开数据库连接
conn.Open();
Console.WriteLine("欢迎使用学生选课系统!");
while (true)
{
Console.WriteLine("请选择您要进行的操作:");
Console.WriteLine("1. 登录");
Console.WriteLine("2. 注册");
Console.WriteLine("3. 退出");
string choice = Console.ReadLine();
if (choice == "1")
{
Console.WriteLine("请输入用户名:");
string username = Console.ReadLine();
Console.WriteLine("请输入密码:");
string password = Console.ReadLine();
// 查询数据库,验证登录信息
string sql = "SELECT * FROM Students WHERE Username=@Username AND Password=@Password";
SqlCommand cmd = new SqlCommand(sql, conn);
cmd.Parameters.AddWithValue("@Username", username);
cmd.Parameters.AddWithValue("@Password", password);
SqlDataReader reader = cmd.ExecuteReader();
if (reader.Read())
{
Console.WriteLine("登录成功!");
// 显示选课信息
string sql2 = "SELECT * FROM Courses";
SqlCommand cmd2 = new SqlCommand(sql2, conn);
SqlDataReader reader2 = cmd2.ExecuteReader();
Console.WriteLine("可选课程列表:");
Console.WriteLine("------------------------");
while (reader2.Read())
{
Console.WriteLine(reader2["CourseName"] + "(" + reader2["TeacherName"] + ")");
}
}
else
{
Console.WriteLine("用户名或密码错误,登录失败!");
}
reader.Close();
}
else if (choice == "2")
{
Console.WriteLine("请输入用户名:");
string username = Console.ReadLine();
Console.WriteLine("请输入密码:");
string password = Console.ReadLine();
// 将注册信息插入到数据库
string sql = "INSERT INTO Students (Username, Password) VALUES (@Username, @Password)";
SqlCommand cmd = new SqlCommand(sql, conn);
cmd.Parameters.AddWithValue("@Username", username);
cmd.Parameters.AddWithValue("@Password", password);
int rows = cmd.ExecuteNonQuery();
if (rows > 0)
{
Console.WriteLine("注册成功!");
}
else
{
Console.WriteLine("注册失败!");
}
}
else if (choice == "3")
{
break;
}
else
{
Console.WriteLine("输入错误,请重新输入!");
}
}
// 关闭数据库连接
conn.Close();
}
}
}
```
上面的代码演示了一个简单的学生选课系统,包括登录、注册和退出操作。在实际开发中,你还需要根据具体需求添加更多功能。