using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Com.Dys.Model { class User { private int id; private string username; private string password; public int Id { get { return this.id; } set { this.id = value; } } public string Username { get { return this.username; } set { this.username = value; } } public string Password { get { return this.password; } set { this.password = value; } } public User() { } public User(int id, string username, string password) { this.id = id; this.username = username; this.password = password; } } }
using System; using System.Collections.Generic; using System.Data.SqlClient; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Com.Dys.Utils { class DBUtils { public static SqlDataReader GetSQLDataReader(string Sql) { try { string SqlConnection = "server=127.0.0.1;database=dingyingsi;uid=sa;pwd=dys123;"; //windows身份验证 //string sqlconn = "server=(local);database=keede1228;integrated security=SSPI;"; SqlConnection Connection = new SqlConnection(SqlConnection); Connection.Open(); SqlCommand Command = new SqlCommand(Sql, Connection); SqlDataReader Reader = Command.ExecuteReader(); return Reader; } catch (Exception e) { Console.WriteLine(e.Message); Console.ReadLine(); } return null; } } }
using System; using System.Collections; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Com.Dys.Model; using Com.Dys.Utils; using System.Data.SqlClient; namespace Demo01 { class Demo { static void Main(string[] args) { string Sql = "select id, username, password from [user]"; SqlDataReader Reader = DBUtils.GetSQLDataReader(Sql); IEnumerable Users = Encapsulate(Reader); foreach(User user in Users) { Console.WriteLine("id = {0}", user.Id); Console.WriteLine("username = {0}", user.Username); Console.WriteLine("password = {0}", user.Password); } Console.ReadLine(); } static IEnumerable Encapsulate(SqlDataReader Reader) { ArrayList al = new ArrayList(); User user = null; if (Reader == null) { return null; } while (Reader.Read()) { user = new User(); user.Id = (int)Reader["id"]; user.Username = (string)Reader["username"]; user.Password = (string)Reader["password"]; al.Add(user); } return al; } } }