建文件夹:定义数据连接类、数据访问类、实体类
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Data.SqlClient; namespace 实体类_数据访问类_数据连接类 { //数据连接类 class DataConnection { private static string connstr = "server=.; database=mydb; user=sa; pwd=ray;"; public static SqlConnection Conn { get { return new SqlConnection(connstr); } } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Data.SqlClient; namespace 实体类_数据访问类_数据连接类 { //数据访问类 class CarData { private SqlConnection _conn; //连接对象 private SqlCommand _cmd; private SqlDataReader _dr; public CarData() //构造函数:初始化对象 { _conn = DataConnection.Conn; _cmd = _conn.CreateCommand(); }
/// <summary> /// 查询Car表中指定数据 /// </summary> /// <param name="name">编号</param> /// <returns>List<T></returns> public List<Car> Select(string name) { _cmd.CommandText = "select *from Car where Name like @name"; _cmd.Parameters.Clear(); _cmd.Parameters.AddWithValue("@name","%"+name+"%"); _conn.Open(); _dr = _cmd.ExecuteReader(); List<Car> list = new List<Car>(); //实例化List<Car> if (_dr.HasRows) { while (_dr.Read()) { Car c = new Car(); //实例化Car c.Code = _dr["Code"].ToString(); c.Name = _dr["Name"].ToString(); c.Oil = Convert.ToDouble(_dr["Oil"]); c.Powers = Convert.ToInt32(_dr["Powers"]); c.Price = Convert.ToDecimal(_dr["Price"]); list.Add(c); //将查询出的数据放入list中 } } _conn.Close(); return list; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace 实体类_数据访问类_数据连接类 {
//实体类 class Car { private string _code; public string Code { get { return _code; } set { _code = value; } } private string _name; public string Name { get { return _name; } set { _name = value; } } private double _oil; public double Oil { get { return _oil; } set { _oil = value; } } private int _powers; public int Powers { get { return _powers; } set { _powers = value; } } private decimal _price; public decimal Price { get { return _price; } set { _price = value; } } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace 实体类_数据访问类_数据连接类 { class Program { static void Main(string[] args) { Console.Write("请输入要查询的名称:"); string name = Console.ReadLine(); CarData dd = new CarData(); List<Car> list = dd.Select(name); //使用foreach遍历集合 foreach (Car data in list) { Console.WriteLine(data.Code+" "+data.Name+" "+data.Oil+" "+data.Powers+" "+data.Price); //foreach中不能改变元素的结构 //if (data.Code == "c001") //{ // list.Remove(data); //} } Console.ReadLine(); } } }