利用c#面向对象实现对数据库的操作

View Code
 1 using System;
 2 using System.Data;
 3 using System.Data.SqlClient;
 4 using System.Collections.Generic;
 5 using System.Linq;
 6 public class StudyModel
 7 {
 8     public static void Main()
 9     {
10         string strcon = "server = .;database = blog;uid = sa;pwd = 1;";
11         SqlConnection con = new SqlConnection(strcon);
12         SqlCommand cmd = new SqlCommand();
13         cmd.Connection = con;
14         cmd.CommandText = "select * from employee";
15         con.Open();
16         SqlDataReader reader = cmd.ExecuteReader(); 
17         List<Employee> list = new List<Employee>();
18         Employee p = null;
19         while (reader.Read())
20         {
21             p = new Employee();            
22             p.Name = reader["name"].ToString();
23             p.Age = Convert.ToInt32(reader["age"]);
24             p.Sex = Convert.ToInt32(reader["sex"]);
25             list.Add(p);
26         }
27         var result = from a in list
28                      where a.Age >30
29                      select a;
30         foreach (Employee q in result)
31         {
32             Console.WriteLine(q.Name);
33         }
34         reader.Close();
35         cmd.Dispose();
36         con.Close();
37         Console.WriteLine("表中共有"+list.Count+"条数据");        
38     }
39     public class Employee
40     {
41         private string name;
42         private int age;
43         private int sex;
44         public string Name
45         {
46             get{return this.name;}
47             set{this.name = value;}
48         }
49         public int Age
50         {
51             get{return this.age;}
52             set{this.age = value;}
53         }
54         public int Sex
55         {
56             get{return this.sex;}
57             set{this.sex = value;}
58         }
59     }
60 }

 利用c#面向对象 一切皆对象的原理,把数据库中的表创建为对象,表中的字段为对象的属性。这样连接数据库之后只要对对象操作就可以实现对数据库中数据的操作;

posted @ 2012-08-08 20:20  晓 漪  阅读(1090)  评论(2)    收藏  举报