標籤:winform style blog http io color ar os 使用
在winform 資料庫設計中,有時候需要通過條件查詢對應的資料,並且將資料顯示在文字框(or 富文字框)中,下面,小編將講述通過一個條件:
首先,我們需要對資料庫建立串連,並且執行資料庫命令,在此之前,我們先建立一個winform表單,表單設計大概如下所示:
在建立表單後,我們應該進行書寫代碼階段:
1 string s = "server=SAM_PC;database=MInformationDB;Integrated Security=true"; 2 SqlConnection con = new SqlConnection(s); 3 con.Open(); 4 string sql =string.Format( "select * from Student where Grade=‘{0}‘",textBox1.Text); 5 SqlCommand command = new SqlCommand(sql, con); 6 7 SqlDataReader reader = command.ExecuteReader(); 8 while (reader.Read()) 9 {10 string id = (String)reader["Id"];11 string name = (String)reader["Name"];12 int age = (int)reader["Age"];13 string gender = (string)reader["Gender"];14 string major = (string)reader["Major"];15 textBox2.Text += String.Format("{0}\t{1}\t{2}\t{3}\t{4}\r\n", id, name, age, gender, major);16 }
---->
SKILLS:
-----------當查詢結果可能返回多行多列時,需要使用DataReader讀取返回的資料
DataReader的功能是每次一行從讀取資料主要方法:-----------Read方法:從資料庫讀取一行資料,返回bool,為true說明讀取到了資料,false說明已經全部讀取完成,無資料可讀了。-----------[“列名”]:取得當前行某欄位的值,返回object類型,通常要類型轉換-----------Close:使用完畢後關閉,釋放資源 讀取資料的步驟:-----------(0)建立串連、建立命令、開啟串連同前-----------(1)SqlCommand.ExecuteReader返回一個SqlDataReader對象-----------(2)SqlDataReader.Read方法讀取一行資料-----------(3)SqlDataReader[“列名”]讀取當前行的某一列,為object類型,需要類型轉換-----------(4)重複執行(3)步驟讀取其他欄位-----------(5)轉到(2)讀取下一行資料
C# winform表單設計-通過條件查詢資料