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 DBConnect 12 { 13 private static string connstring = "server=.;database=mydb;user=sa;pwd=123"; 14 15 public static SqlConnection Conn 16 { 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 Nation 10 { 11 private string code; 12 13 public string Code 14 { 15 get { return code; } 16 set { code = value; } 17 } 18 private string name; 19 20 public string Name 21 { 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 NationDA 12 { 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 else 40 { 41 return false; 42 } 43 } 44 45 //查询所有数据的方法 46 public List<Nation> Select() 47 { 48 _cmd.CommandText = "select * from Nation"; 49 _conn.Open(); 50 _dr = _cmd.ExecuteReader(); 51 _conn.Close(); 52 53 //定义一个空的集合 54 List<Nation> list = new List<Nation>(); 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 Program 10 { 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 else 26 { 27 Console.WriteLine("添加失败!"); 28 } 29 30 31 Console.ReadLine(); 32 } 33 } 34 }