查詢基礎和連接數據庫

歡迎來到unity學習unity培訓unity企業培訓教育專區,這裏有很多U3D資源U3D培訓視頻U3D教程我們致力於打造業內unity3d培訓學習第一品牌。

今天學習了查詢基礎和連接數據庫

 

查詢基礎

 

什麼是查詢?

 

    查詢產生一個虛擬表,看到的是表形式顯示的結果,但結果並不真正存儲,每次執行查詢只是現從數據表中提取數據,並按照表的形式顯示出來。

如何查詢?

 

--查詢全部數據

 

    select * from <表名>

 

    例:select * from stu

 

既然查詢得到的“結果集”的結構類似於一張表,那麼可以在“結果集”上繼續進行查詢嗎?

--查詢部分數據

 

    select id,name from users where name='張三' --查詢表中name爲‘張三’的數據

 

    select id,name from users where name<>'張三' --查詢表中那麼不爲‘張三’的數據

 

去掉重複字段查詢記錄

 

    select distinct name from student

 

合併查詢(合併兩表中相同的字段)

 

     select * from student union select * from score

 

命名

 

--用AS來命名列

 

    select id as 編號,name as 姓名 from users

 

--用 = 來命名列

 

    select 編號 =id ,姓名=name  from users

 

---查詢空行

 

    select id, name from users where password is null

 

--查詢非空行

 

    select name from users where name is not null

 

--使用常量列(默認值)

 

    select name as  姓名 ,'密碼' as password from users

 

    User中所有password都會變爲‘密碼’兩個字

 

--限制固定行數

 

    select top 3 * from users

 

--返回百分之多少行

 

    select top 50 percent * from users

 

--升序

 

    select * from users order by idselect * from users order by id asc

 

--降序

 

    select * from users order by id desc

 

--按多列排序(當排序的值相同時,按第二個字段排序)

 

    select * from users order by name,id

 

連接數據庫

 

程序訪問數據庫的步驟:

 

    開 始>引入命名空間 >創建一個 SqlConnection 對象>打開連接>創建一個SqlCommand對象>關閉連接>關閉SqlDataReader對象>獲取SqlDataReader對象>結 束

 

引入命名空間:

 

    using System.Data;

    using System.Data.SqlClient;

訪問:

    public void Get

    {

           SqlConnection con = new SqlConnection("server=127.0.0.1;uid=sa; pwd =wang;database =second");

           SqlCommand cmd=new SqlCommand("select * from users",con);

           con.Open();

                SqlDataReader myreader=cmd.ExecuteReader();

                 while (myreader.Read())

                {

                Console.WriteLine(myreader.GetValue(0) + "   " +  

                myreader.GetValue(1));   

                }

              myreader.Close();

              con.Close(); 

    }

 

   更多精彩內容請關注:http://www.gopedu.com/

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章