使用c#面向对象实现对数据库的操作的代码,供大家学习参考。
复制代码 代码如下:
using System;
using System.Data;
using System.Data.SqlClient;
using System.Collections.Generic;
using System.Linq;
public class StudyModel
{
public static void Main()
{
string strcon = "server = .;database = blog;uid = sa;pwd = 1;";
SqlConnection con = new SqlConnection(strcon);
SqlCommand cmd = new SqlCommand();
cmd.Connection = con;
cmd.CommandText = "select * from employee";
con.Open();
SqlDataReader reader = cmd.ExecuteReader();
List<Employee> list = new List<Employee>();
Employee p = null;
while (reader.Read())
{
p = new Employee();
p.Name = reader["name"].ToString();
p.Age = Convert.ToInt32(reader["age"]);
p.Sex = Convert.ToInt32(reader["sex"]);
list.Add(p);
}
var result = from a in list
where a.Age >30
select a;
foreach (Employee q in result)
{
Console.WriteLine(q.Name);
}
reader.Close();
cmd.Dispose();
con.Close();
Console.WriteLine("表中共有"+list.Count+"条数据");
}
public class Employee
{
private string name;
private int age;
private int sex;
public string Name
{
get{return this.name;}
set{this.name = value;}
}
public int Age
{
get{return this.age;}
set{this.age = value;}
}
public int Sex
{
get{return this.sex;}
set{this.sex = value;}
}
}
}
备注:
使用c#面向对象的方法,把数据库中的表创建为对象,表中的字段为对象的属性。
这样连接数据库后,只要对对象操作就可以实现对数据库中数据的操作。