标签:and sof sel lda ctp 工作 不同 行操作 HERE
在.NET世界,如果想要对数据库进行操作,总少不了ADO.NET的身影。在.NET Core里同样离不开那些熟悉的类库与API。这里简略地介绍下如何通过ADO.NET对SQL Server进行不同的处理。
第一步先在项目工程中查看有无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"]);
}
}
}
}
使用上与普通的数据表没有差别。
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 CTP3
.NET Core开发日志——ADO.NET与SQL Server
标签:and sof sel lda ctp 工作 不同 行操作 HERE
原文地址:https://www.cnblogs.com/kenwoo/p/9563015.html