C#從MySQL資料庫中讀取
阿新 • • 發佈:2018-11-26
實現了資料庫的建表、儲存資料的功能後,還需要實現資料庫的讀取,綜合查資料後發現有兩種發發比較好;
一、如u需要介面操作,需要將資料表格在介面上顯示出來的話,需要使用DataGrid控制元件。
基本操作流程:宣告一個數據介面卡和資料集,並將讀取指令賦值給資料介面卡的指令,開啟資料庫,執行資料介面卡的指令,然後將介面卡讀取的資料填充到資料集中,最後將資料集通過DATAGrid的控制元件顯示出來。
string myConn="server=127.0.0.1;uid=data;database=test;Trusted_Connection=no"; //定義資料庫連線引數 SqlConnection MyConnection=new SqlConnection(MyConn); //定義一個數據連線例項 SqlCommand MyCommand=new SqlCommand("SELECT wavelength FROM data",MyConnection); //定義一個數據庫操作指令 SqlDataAdapter SelectAdapter=new SqlDataAdapter(); //定義一個數據介面卡 SelectAdapter.SelectCommand=MyCommand; //定義資料介面卡的操作指令 DataSet MyDataSet=new DataSet(); //定義一個數據集 MyConnection.Open(); //開啟資料庫連線 SelectAdapter.SelectCommand.ExecuteNonQuery(); //執行資料庫查詢指令 MyConnection.Close(); //關閉資料庫 SelectAdapter.Fill(MyDataSet); //填充資料集 DataGrid1.DataSource=MyDataSet; DataGrid1.DataBind(); //將資料表格用資料集中的資料填充
二、通過SqlDataReader直接讀取資料庫中某行或者某列的資料
//1.構建資料庫查詢語句,X為你所查詢的值所在的列名,table 為你儲存資料的表名。string sql = "select x from [table]"; //2.資料庫查詢 SqlConnection conn = new SqlConnection(_connstring); SqlCommand command = new SqlCommand(sql, conn); //3.執行資料庫查詢獲取返回值 List<string> list = new List<string>(); use(conn) { conn.Open(); SqlDataReader reader = command.ExecuteReader(); while(reader.read()) { for(int i=0;i<reader.FiledCount;i++) { list.Add(reader[i].ToString()); } }