在.NET世界,若是想要對數據庫進行操做,總少不了ADO.NET的身影。在.NET Core裏一樣離不開那些熟悉的類庫與API。這裏簡略地介紹下如何經過ADO.NET對SQL Server進行不一樣的處理。sql
第一步先在項目工程中查看有無System.Data.SqlClient引用,若是沒有的話,能夠用如下三種方式安裝:數據庫
Install-Package System.Data.SqlClient
dotnet add package System.Data.SqlClient
能夠使用最基礎的ExecuteReader方法:工具
using (var conn = new SqlConnection("Server=.;Integrated Security=true")) { conn.Open(); using (var cmd = new SqlCommand("select top 10 * from [AdventureWorks2016CTP3].[Person].[Person]", conn)) { using (var reader = cmd.ExecuteReader()) { while (reader.Read()) { Console.WriteLine(reader["FirstName"]); } } } }
在.NET Core 2.0之後還能夠使用SqlDataAdapter與DataSet,看得出微軟在向後兼容方面作了很多工做:命令行
using (var conn = new SqlConnection("Server=.;Integrated Security=true")) { var adapter = new SqlDataAdapter("select top 10 * from [AdventureWorks2016CTP3].[Person].[Person]", conn); var dataset = new DataSet(); adapter.Fill(dataset); var dt = dataset.Tables[0]; foreach (var item in dt.Rows) { var row = item as DataRow; Console.WriteLine(row["FirstName"]); } }
using (var conn = new SqlConnection("Server=.;Integrated Security=true")) { conn.Open(); using (var cmd = new SqlCommand("insert into [AdventureWorks2016CTP3].[Person].[AddressType] (Name) values(@Name)", conn)) { cmd.Parameters.AddWithValue("@Name", "Test"); cmd.ExecuteNonQuery(); } }
using (var conn = new SqlConnection("Server=.;Integrated Security=true")) { conn.Open(); using (var cmd = new SqlCommand("update [AdventureWorks2016CTP3].[Person].[AddressType] set name = @Name where name = @Criterion", conn)) { cmd.Parameters.AddWithValue("@Name", "Test2"); cmd.Parameters.AddWithValue("@Criterion", "Test"); cmd.ExecuteNonQuery(); } }
using (var conn = new SqlConnection("Server=.;Integrated Security=true")) { conn.Open(); using (var cmd = new SqlCommand("delete [AdventureWorks2016CTP3].[Person].[AddressType] where name = @Name", conn)) { cmd.Parameters.AddWithValue("@Name", "Test2"); cmd.ExecuteNonQuery(); } }
using (var conn = new SqlConnection("Server=.;Integrated Security=true")) { conn.Open(); using (var cmd = new SqlCommand("[AdventureWorks2016CTP3].[dbo].[uspGetEmployeeManagers]", conn)) { cmd.CommandType = CommandType.StoredProcedure; cmd.Parameters.AddWithValue("@BusinessEntityID", 10); using (var reader = cmd.ExecuteReader()) { while (reader.Read()) { Console.WriteLine(reader["FirstName"]); } } } }
使用上與普通的數據表沒有差異。code
using (var conn = new SqlConnection("Server=.;Integrated Security=true")) { conn.Open(); using (var cmd = new SqlCommand("select top 10 * from [AdventureWorks2016CTP3].[HumanResources].[vEmployee]", conn)) { using (var reader = cmd.ExecuteReader()) { while (reader.Read()) { Console.WriteLine(reader["FirstName"]); } } } }
以上代碼例子裏的數據庫使用的是AdventureWorks Databases and Scripts for SQL Server 2016 CTP3ip