用C#简单实现了数据的封装
/*
*说明:一共四个.cs文件。DBHelp类实现了连接数据库,StudentDao类实现了数据的逻辑上的处理,student为实体类, Program测试类
*时间:2013.11.4
*作者:Mr.Smart
*/
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 using System; 2 using System.Data; 3 using System.Data.Sql; 4 using System.Data.SqlClient; 5 using System .Text; 6 7 namespace Demo 8 { 9 /// <summary> 10 /// Description of DBHElp. 11 /// </summary> 12 public class DBHElp 13 { 14 public DBHElp() 15 { 16 } 17 18 //返回一个数据库连接 19 public static SqlConnection sqlcon(string database) 20 { 21 string conText = string.Format(@"server = .; database ={0};Integrated Security= sspi",database); 22 return new SqlConnection (conText); 23 } 24 } 25 }
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 namespace Demo 2 { 3 /// <summary> 4 /// Description of StudentDao. 5 /// </summary> 6 public class StudentDao 7 { 8 public StudentDao() 9 { 10 } 11 public void AddToDatabase(Student stu) 12 { 13 SqlConnection sc = DBHElp.sqlcon("db_stu"); 14 string cmdText = "insert into student(Names,Sex,Age) values(@names,@sex,@age)"; 15 SqlCommand cmd = new SqlCommand(cmdText,sc); 16 cmd.Parameters.Add("@names",SqlDbType.VarChar).Value = stu.stuName; 17 cmd.Parameters.Add("@sex",SqlDbType.VarChar).Value = stu.stuSex; 18 cmd.Parameters.Add("@age",SqlDbType.Int).Value=stu.stuAge; 19 try 20 { 21 sc.Open(); 22 int i = cmd.ExecuteNonQuery(); 23 if(i>0) 24 { 25 Console.WriteLine("insert success !"); 26 } 27 else 28 { 29 Console.WriteLine("insert failed!"); 30 } 31 } 32 catch(Exception ex) 33 { 34 Console.WriteLine("ERROR :"+ex.Message); 35 } 36 finally 37 { 38 if(sc.State== ConnectionState.Open) 39 { 40 sc.Close(); 41 } 42 } 43 } 44 45 } 46 }
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 using System; 2 using System.Text; 3 using System.Collections; 4 using System.Collections.Generic; 5 6 namespace Demo 7 { 8 /// <summary> 9 /// Description of Student. 10 /// </summary> 11 public class Student 12 { 13 //对象初始化构造器 14 public string stuName{get;set;} 15 public string stuSex{get;set;} 16 public int stuAge{get;set;} 17 18 public Student() 19 { 20 21 } 22 23 public Student(string stuName,string stuSex,int stuAge){ 24 this.stuName = stuName; 25 this.stuSex = stuSex; 26 this.stuAge = stuAge; 27 } 28 29 } 30 }
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 namespace Demo 2 { 3 class Program 4 { 5 public static void Main(string[] args) 6 { 7 Student stu = new Student("蜡笔小新","男",10); 8 StudentDao stuDao = new StudentDao(); 9 stuDao.AddToDatabase(stu); 10 Console.ReadKey(); 11 } 12 } 13 }