练习为了方便,没有使用自增id,也没实现删除和修改,跟新增类似。
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace TestConnect
{
public class Program
{
static void Main(string[] args)
{
Console.WriteLine("学生管理系统");
Console.WriteLine("********************************");
Program.selectStudent();
bool isxunhuan = true;
for (; isxunhuan;) {
Console.WriteLine("请选择要做的操作1.新增2.修改3.删除4.退出系统");
int zhixiang = int.Parse(Console.ReadLine());
switch (zhixiang)
{
case 1:
Console.WriteLine("请输入要添加的学生姓名:");
string name = Console.ReadLine();
Console.WriteLine("请输入 年龄:");
string age = Console.ReadLine();
Console.WriteLine("请输入备注:");
string remark = Console.ReadLine();
string sql = $"insert into student values ('{name}','{age}','{remark}')";
if (Program.EditData(sql)>0)
Console.WriteLine("添加成功");
else
Console.WriteLine("添加失败");
Program.selectStudent();
break;
case 2:
Console.WriteLine("执行修改操作");
break;
case 3:
Console.WriteLine("执行删除操作");
break;
case 4:
isxunhuan = false;
Console.WriteLine("已退出系统");
break;
default:
Console.WriteLine("请重新输入");
break;
}
}
Console.ReadKey();
}
public static int EditData(string sql)
{
SqlConnection sqlConnection = new SqlConnection("Data Source=.;Initial Catalog=School;Integrated Security=True;");
sqlConnection.Open();
SqlCommand cmd = new SqlCommand(sql, sqlConnection);
int count = 0;
try
{
count = cmd.ExecuteNonQuery();
sqlConnection.Close();
return count;
}
catch (Exception ex)
{
Console.WriteLine(ex);
throw;
}
}
public static DataTable SelectData(string sql)
{
SqlConnection sqlConnection = new SqlConnection("Data Source=.;Initial Catalog=School;Integrated Security=True;");
sqlConnection.Open();
SqlCommand cmd = new SqlCommand(sql, sqlConnection);
SqlDataAdapter adapter = new SqlDataAdapter(cmd);
DataSet set = new DataSet();
adapter.Fill(set);
return set.Tables[0];
}
public static void selectStudent()
{
string selectstudent = "select * from student";
DataTable stutable = SelectData(selectstudent);
Console.WriteLine("姓名 年龄 备注");
for (int i = 0; i < stutable.Rows.Count; i++)
{
Console.WriteLine(stutable.Rows[i]["Name"] + " " + stutable.Rows[i]["Age"] + " " + stutable.Rows[i]["Remark"]);
}
}
}
}