csharp Sql Server Ado.NET
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了csharp Sql Server Ado.NET相关的知识,希望对你有一定的参考价值。
USE [NORTHWND]
GO
/****** Object: StoredProcedure [dbo].[GetAllEmployeeDetails] Script Date: 06/09/2017 17:11:47 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[GetAllEmployeeDetails]
AS
BEGIN
SET NOCOUNT ON;
SELECT FirstName, LastName, BirthDate, City, Country
FROM Employees
END
GO
var connString = ConfigurationManager.ConnectionStrings["myConnectionString"].ConnectionString;
List<Employee> employees1 = new List<Employee>();
using (var conn = new SqlConnection(connString))
{
conn.Open();
var cmd = new SqlCommand("SELECT * FROM Employees WHERE EmployeeID > @valore ORDER BY EmployeeID DESC", conn);
cmd.Parameters.AddWithValue("@valore", 5);
using (var reader = cmd.ExecuteReader())
{
while (reader.Read())
{
var employeeID = Convert.ToInt32(reader["EmployeeID"]);
string lastName = reader["LastName"].ToString();
string firstName = reader["FirstName"].ToString();
employees1.Add(new Employee
{
EmployeeID = employeeID,
LastName = lastName,
FirstName = firstName
});
}
}
cmd.Dispose();
}
using (var conn = new SqlConnection(connString))
{
conn.Open();
SqlTransaction myTrans = conn.BeginTransaction();
var cmd = new SqlCommand("UPDATE Employees SET LastName = @lastName WHERE EmployeeID = @valore", conn);
cmd.Parameters.AddWithValue("@lastName", "Gates");
cmd.Parameters.AddWithValue("@valore", 5);
cmd.Transaction = myTrans;
try
{
var numRowsAffected = cmd.ExecuteNonQuery();
cmd.Transaction.Commit();
}
catch (Exception e)
{
try
{
myTrans.Rollback();
}
catch (SqlException ex)
{
if (myTrans.Connection != null)
{
Console.WriteLine("An exception of type " + ex.GetType() +
" was encountered while attempting to roll back the transaction.");
}
}
}
cmd.Dispose();
}
List<Employee> employees2 = new List<Employee>();
using (var conn = new SqlConnection(connString))
{
SqlCommand cmd = new SqlCommand("GetAllEmployeeDetails", conn);
cmd.CommandType = CommandType.StoredProcedure;
//SqlParameter RetVal = cmd.Parameters.Add("RetVal", SqlDbType.Int);
//RetVal.Direction = ParameterDirection.ReturnValue;
//SqlParameter IdIn = cmd.Parameters.Add("@au_idIN", SqlDbType.VarChar, 11);
//IdIn.Direction = ParameterDirection.Input;
//SqlParameter NumTitles = cmd.Parameters.Add("@numtitlesout", SqlDbType.VarChar, 11);
//NumTitles.Direction = ParameterDirection.Output;
conn.Open();
using (SqlDataReader reader = cmd.ExecuteReader())
{
while (reader.Read())
{
string lastName = reader["LastName"].ToString();
string firstName = reader["FirstName"].ToString();
employees2.Add(new Employee
{
LastName = lastName,
FirstName = firstName
});
};
}
}
以上是关于csharp Sql Server Ado.NET的主要内容,如果未能解决你的问题,请参考以下文章
如何为 SQL Server 和 SQL Server Compact 编写相同的 ado.net 代码?
使用 ADO.NET 将数据表从内存推送到 SQL Server
C#:通过 ADO.NET 在 SQL Server 2008 上运行事务