最近在學習C#與sql server2019的互動,記錄一下學習總結,
1、c#連接資料庫并讀取資料庫表格,
SqlConnection conn = new SqlConnection(); //定義資料庫連接 conn.ConnectionString = "Server= 服務器名 ;DataBase= 資料庫名稱 ;Trusted_Connection=SSPI"; //定義連接字串 conn.Open(); //打開 資料庫連接
2、連接資料庫后開始定位到資料然后讀取
str sql = "select * from 表名 " ;
//定義字串," "中的字串可以在sql server中運行,運行結果就是一會要讀取的資料表,表名為上面資料庫名稱里面的表;
SqlCommand sqlcomm = new SqlCommand(sql, conn);
//連接到表 SqlDataReader reader = sqlcomm.ExecuteReader();
//讀取 Int64 id=0,channel=0;
//定義int型別,跟資料中資料的存盤型別相對應 where(reader.read())
//資料按行讀取,每讀一行回圈一次,讀完一行開始下一行,直到讀取結束,這里假設資料庫中只有一行值 { id = (Int64)reader["id"];
//reader[" "]中的id名為資料庫中列名 channel = (Int32)reader["channel"]; } Console.WriteLine(id + " "+channel);
//輸出id、channel,其中id 和channel輸出的值應 等于 資料庫中對應的表第一行中列名為id、channel的值 reader.close();
//關閉閱讀 conn.Close();
//關閉資料庫連接 conn.Dispose();
//釋放資源
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/285394.html
標籤:.NET技术
上一篇:WPF實作音樂字幕影片
