config文件
<?xml version="1.0" encoding="utf-8" ?> <configuration> <startup> <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.7.2" /> </startup> <connectionStrings> <add name="connString" connectionString="server=LIN;database=Excel;uid=sa;pwd=123456"/> </connectionStrings> </configuration>
实体类:
namespace Models { public class TestBackup { public int id { get; set; } public string name { get; set; } public int age { get; set; } public DateTime time { get; set; } } }
数据模块:
namespace DAL { public class TestBackupService { private static string connString= ConfigurationManager.ConnectionStrings["connString"].ToString();public static List<TestBackup> Select() { SqlConnection conn = new SqlConnection(connString) ; string sql = $"select * from testBackup"; SqlCommand cmd= new SqlCommand(sql,conn); SqlDataReader count = null; try { conn.Open(); count = cmd.ExecuteReader(CommandBehavior.CloseConnection); List<TestBackup> testBackups= new List<TestBackup>();
//循环把查询赋给集合 while (count.Read()) { TestBackup testBackup = new TestBackup() { id = Convert.ToInt32(count["id"].ToString()),//重点 name = count["Tname"].ToString(), age = Convert.ToInt32(count["age"].ToString()), time = Convert.ToDateTime(count["datetime"].ToString()) }; testBackups.Add(testBackup); } return testBackups; } catch (Exception ex) { string msg = $"{DateTime.Now.ToString()}执行方法:public static SqlDataReader Select()错误"; msg+= ex.Message; throw new Exception(msg); return null; } } } }
业务类:
public static void SelectBackup() { try { List<TestBackup> tsxts=TestBackupService.Select(); foreach (TestBackup tst in tsxts) { Console.WriteLine($"{tst.id}\t{tst.name}\t{tst.age}\t{tst.time}"); } }catch (Exception ex) { Console.WriteLine(ex.Message); } }
标签:count,实体类,查询,set,ToString,new,tst,public,赋值 From: https://www.cnblogs.com/lin-07/p/17391819.html