在操作数据库时,将数据方法封装为不同类,增加程序的可读性
提供数据连接对象的类
1 using System; 2 using System.Collections.Generic; 3 using System.Linq; 4 using System.Text; 5 using System.Threading.Tasks; 6 using System.Data.SqlClient; 7 8 namespace ConsoleApplication1 9 {10 //提供数据连接对象11 public class DBConnect12 {13 private static string connstring = "server=.;database=mydb;user=sa;pwd=123";14 15 public static SqlConnection Conn16 {17 get {18 return new SqlConnection(connstring);19 }20 }21 }22 }
建立属性
1 using System; 2 using System.Collections.Generic; 3 using System.Linq; 4 using System.Text; 5 using System.Threading.Tasks; 6 7 namespace ConsoleApplication1 8 { 9 public class Nation10 {11 private string code;12 13 public string Code14 {15 get { return code; }16 set { code = value; }17 }18 private string name;19 20 public string Name21 {22 get { return name; }23 set { name = value; }24 }25 }26 }
封装运算方法
1 using System; 2 using System.Collections.Generic; 3 using System.Linq; 4 using System.Text; 5 using System.Threading.Tasks; 6 using System.Data.SqlClient; 7 8 namespace ConsoleApplication1 9 {10 //主要实现对Nation表的各种操作(增删改查)11 public class NationDA12 {13 private SqlConnection _conn; //连接对象14 private SqlCommand _cmd; //命令对象15 private SqlDataReader _dr; //读取器对象16 17 //构造方法来初始化连接对象 命令对象18 public NationDA()19 {20 _conn = DBConnect.Conn; //对连接对象进行初始化21 _cmd = _conn.CreateCommand(); //对命令对象进行初始化22 }23 24 //添加数据的方法25 public bool Add(string code,string name)26 {27 _cmd.CommandText = "insert into Nation values(@code,@name)";28 _cmd.Parameters.AddWithValue("@code",code);29 _cmd.Parameters.AddWithValue("@name",name);30 31 _conn.Open();32 int n = _cmd.ExecuteNonQuery();33 _conn.Close();34 35 if (n > 0)36 {37 return true;38 }39 else40 {41 return false;42 }43 }44 45 //查询所有数据的方法46 public ListSelect()47 {48 _cmd.CommandText = "select * from Nation";49 _conn.Open();50 _dr = _cmd.ExecuteReader();51 _conn.Close();52 53 //定义一个空的集合54 List list = new List ();55 56 if (_dr.HasRows)57 {58 while (_dr.Read())59 {60 //造一个Nation对象61 Nation data = new Nation();62 data.Code = _dr[0].ToString();63 data.Name = _dr[1].ToString();64 65 //扔到集合里面66 list.Add(data);67 }68 }69 70 return list;71 }72 }73 }
主函数调用
1 using System; 2 using System.Collections.Generic; 3 using System.Linq; 4 using System.Text; 5 using System.Threading.Tasks; 6 7 namespace ConsoleApplication1 8 { 9 class Program10 {11 static void Main(string[] args)12 {13 Console.WriteLine("请输入代号:");14 string code = Console.ReadLine();15 16 Console.WriteLine("请输入名称:");17 string name = Console.ReadLine();18 19 NationDA da = new NationDA();20 21 if (da.Add(code, name))22 {23 Console.WriteLine("添加成功!");24 }25 else26 {27 Console.WriteLine("添加失败!");28 }29 30 31 Console.ReadLine();32 }33 }34 }