3_05_MSSQL课程_Ado.Net_SQLDataAdapter
1 using System; 2 using System.Collections.Generic; 3 using System.ComponentModel; 4 using System.Configuration; 5 using System.Data; 6 using System.Data.SqlClient; 7 using System.Drawing; 8 using System.Linq; 9 using System.Text; 10 using System.Threading.Tasks; 11 using System.Windows.Forms; 12 13 namespace _01SQLAndAdo.Net 14 { 15 public partial class SqlData2DataGirdView : Form 16 { 17 public SqlData2DataGirdView() 18 { 19 InitializeComponent(); 20 } 21 22 private void SqlData2DataGirdView_Load(object sender, EventArgs e) 23 { 24 25 string connStr = ConfigurationManager.ConnectionStrings["sql"].ConnectionString; 26 string commandText = @"SELECT TOP 1000 [User_ID] 27 ,[User_Name] 28 ,[User_Gender] 29 ,[User_Age] 30 ,[User_Address] 31 ,[User_Birthday] 32 ,[User_Remark] 33 ,[User_Money] 34 ,[User_GUIDDemo] 35 ,[User_Pwd] 36 FROM[LJK_SQLServerDB].[dbo].[User_Info]"; 37 using (SqlConnection conn = new SqlConnection(connStr)) 38 { 39 using (SqlDataAdapter adapter = new SqlDataAdapter(commandText, connStr)) 40 { 41 //DataSet方式,查询多张表的时候应用 42 //DataSet dataSet=new DataSet(); 43 //adapter.Fill(dataSet,"demo"); 44 //this.dgvUserInfo.DataSource = dataSet.Tables["demo"]; 45 46 DataTable dataTable = new DataTable(); 47 //填充之前不需要打开数据库连接,Adaper会自动打开连接,并执行SQL 48 //Fill方法内部: 49 //1. 先判断SqlConnection是否初始化,如果没有打开链接,那么打开连接。 50 //2. 初始化一个Select(commandText) SqlCommand对象 51 //3. 通过cmd对象执行,然后返回一个SqlReader对象。 52 //4. 读取数据库中的数据,然后填充到DataTable上去 53 adapter.Fill(dataTable); //把数据库中的数据 填充到 内存表中 54 //把内存表显示到DataGirdView上去 55 // this.dgvUserInfo.DataSource = dataTable; 56 57 // var o = dataTable.Rows[0][1]; 58 59 // dataRow["列名"]; //弱类型 60 //user.UserInfo //强类型,出错概率下降 61 List<UserInfo> userInfoList = new List<UserInfo>(); 62 foreach (DataRow dataRow in dataTable.Rows) 63 { 64 Console.WriteLine(dataRow["User_Id"] + " " + dataRow[0]); 65 Console.WriteLine(dataRow["User_Name"] + " " + dataRow[1]); 66 Console.WriteLine(dataRow["User_Age"] + " " + dataRow[2]); 67 Console.WriteLine(dataRow["User_Pwd"] + " " + dataRow[3]); 68 UserInfo userInfo = new UserInfo(); 69 userInfo.UserId = int.Parse(dataRow["User_ID"].ToString()); 70 userInfo.UserName = dataRow["User_Name"].ToString(); 71 if (!string.IsNullOrEmpty(dataRow["User_Age"].ToString())) 72 { 73 userInfo.UserAge = int.Parse(dataRow["User_Age"].ToString()); 74 // userInfo.UserAge = dataRow["User_Age"].ToString(); 75 // userInfo.UserAge = 1; 76 } 77 else 78 { 79 userInfo.UserAge = 0; 80 } 81 82 if (!string.IsNullOrEmpty(dataRow["User_Pwd"].ToString())) 83 { 84 userInfo.UserPwd = int.Parse(dataRow["User_Pwd"].ToString()); 85 } 86 else 87 { 88 userInfo.UserPwd = 11; 89 } 90 91 userInfoList.Add(userInfo); 92 93 94 //把DataTabel的数据转成List<UserInfo> 95 96 } 97 98 this.dgvUserInfo.DataSource = userInfoList; 99 100 } 101 102 } 103 104 105 } 106 } 107 }