ADO.NET realizes SQL Server addition, deletion, modification, query and calling of stored procedures

Database structure

The primary key table category cId is associated with the foreign key table product categoryId

Product table

product

category table

category

Stored procedure

  1. getProByName
USE [ProductDB]
GO
/****** Object:  StoredProcedure [dbo].[getProByName]    Script Date: 2020/10/23 13:23:55 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
ALTER proc [dbo].[getProByName]
@name nvarchar(50)
as
begin
  select * from Product a,Category b where a.categoryId=b.cId and a.pName like '%'+@name+'%'
end
  1. getProNum
USE [ProductDB]
GO
/****** Object:  StoredProcedure [dbo].[getProNum]    Script Date: 2020/10/23 13:25:35 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
ALTER procedure [dbo].[getProNum]
@num int output
as
begin
	select @num = COUNT(*) from Product
end
  1. getResult
USE [ProductDB]
GO
/****** Object:  StoredProcedure [dbo].[getResult]    Script Date: 2020/10/23 13:26:03 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
ALTER procedure [dbo].[getResult]
as
begin
	return 666
end
  1. getResultAndNum
USE [ProductDB]
GO
/****** Object:  StoredProcedure [dbo].[getResultAndNum]    Script Date: 2020/10/23 13:27:08 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
ALTER procedure [dbo].[getResultAndNum]
@num int output
as
begin
	select @num = COUNT(*) from Product
	return @num
end

DBHelper

Connection string (configured in the config file)

1.config file configuration

<connectionStrings>
      <add name="constr" connectionString="server=.;database=productdb;uid=sa;pwd=scce;"/>
</connectionStrings>

2. Obtain the connection string in the config file through ConfigurationManager

ConfigurationManager needs to be added in Reference---->Add Reference---->AssemblySystem.ConfigurationQuote

private static string constr = ConfigurationManager.ConnectionStrings["constr"].ConnectionString;

sql query method

//查询
//返回datatable
public static DataTable ExecuteQuery(string sql)
{
    
    
    SqlConnection conn = new SqlConnection(constr);
    conn.Open();
    SqlDataAdapter sda = new SqlDataAdapter(sql, conn);
    DataTable dt = new DataTable();
    sda.Fill(dt);
    conn.Close();
    return dt;
}

sql addition, deletion and modification method

//增删改
//返回影响行数
 public static int ExecuteNonQuery(string sql)
 {
    
    
     SqlConnection conn = new SqlConnection(constr);
     conn.Open();
     SqlCommand com = new SqlCommand(sql, conn);
     int rows = com.ExecuteNonQuery();
     conn.Close();
     return rows;
 }

Call a stored procedure (may not be written rigorously)

First define the method of generating stored procedure parameters
1. Output parameters

/// <summary>
 /// 创建输入参数,返回SqlParameter
 /// </summary>
 /// <param name="name">参数名称</param>
 /// <param name="val">参数值value</param>
 /// <returns>一个 Input SqlParameter对象</returns>
 public static SqlParameter CreateInput(string name,object val)
 {
    
    
     return new SqlParameter
     {
    
    
         ParameterName = name,
         Value = val
     };
 }

2. Output parameters

/// <summary>
/// 创建输出参数,返回SqlParameter
/// </summary>
/// <param name="name">参数名称</param>
/// <param name="type">参数值类别 SqlDbType类型</param>
/// <returns>一个OutPut SqlParameter对象</returns>
public static SqlParameter CreateOutput(string name,SqlDbType type)
{
    
    
    return new SqlParameter
    {
    
    
        ParameterName = name,
        SqlDbType = type,
        Direction = ParameterDirection.Output
    };
}

3.Return value

/// <summary>
/// 创建返回值
/// </summary>
///<param name="type">参数值类别</param>
/// <returns>一个ReturnValue SqlParameter对象</returns>
public static SqlParameter CreateReturn(SqlDbType type)
{
    
    
    return new SqlParameter
    {
    
    
        ParameterName = "@ReturnValue",
        SqlDbType = type,
        Direction = ParameterDirection.ReturnValue
    };
}

Define the method of
executing the stored procedure 1. Execute the stored procedure of the query

/// <summary>
/// 执行查询的存储过程
/// </summary>
/// <param name="procName">存储过程名称</param>
/// <param name="parameters">存储过程参数集</param>
/// <returns>一个DataTable对象</returns>
public static DataTable ExecuteProcedureQuery(string procName,SqlParameter[] parameters)
{
    
    
    SqlConnection conn = new SqlConnection(constr);
    conn.Open();
    SqlCommand command = new SqlCommand(procName, conn);
    command.CommandType = CommandType.StoredProcedure;
    if (parameters != null)
    {
    
    
        command.Parameters.AddRange(parameters);
    }
    DataTable dt = new DataTable();
    using (SqlDataReader sdr = command.ExecuteReader())
    {
    
    
        dt.Load(sdr);
    }
    conn.Close();
    return dt;

}

2. Execute other stored procedures

/// <summary>
/// 执行其他存储过程
/// </summary>
/// <param name="procName">存储过程名</param>
/// <param name="parameters">存储过程参数集</param>
/// <returns>一个字典集合的SqlParameter结果集</returns>
public static IDictionary<string, SqlParameter> ExecuteProcedure(string procName,SqlParameter[] parameters)
{
    
    
    SqlConnection conn = new SqlConnection(constr);
    conn.Open();
    SqlCommand command = new SqlCommand(procName, conn);
    command.CommandType = CommandType.StoredProcedure;
    if (parameters != null)
    {
    
    
        command.Parameters.AddRange(parameters);
    }
    command.ExecuteNonQuery();
    var dict = new Dictionary<string, SqlParameter>();
    foreach (var item in parameters)
    {
    
    
        dict.Add(item.ParameterName, item);
    }
    conn.Close();
    return dict;
}

Call DBHelper

Query method

string querySql = "select * from product a,category b where a.categoryId = b.cId";
var queryResult = DBHelper.ExecuteQuery(querySql);
foreach (DataRow item in queryResult.Rows)
{
    
    
    Console.WriteLine($"{item["pId"]}\t{item["pName"]}\t{item["pPrice"]}\t{item["pStock"]}\t{item["pDesc"]}\t{item["cName"]}");
}

result

Product Number product name Commodity price Commodity stocks product description Product category
1 65-inch Super TV 2599.00 100 4K Ultra Clear HDR123456 Clothing and shoes
2 Drum washing machine 1999.00 50 Fully automatic 10 kg frequency conversion... Household appliances
3 Autumn middle-aged long sleeve T-shirt 159.00 100 Lapel men's autumn base coat... Clothing and shoes
4 Unisex couple baseball cap 298.00 50 The giao language of the peaked cap... Clothing and shoes
5 User Experience Guide: From Methodology to Product Design Practice 98.00 100 The three designers of BAT... Books and Entertainment
6 Knowledge Graph: Methods, Practice and Application 81.00 100 4K ultra-clear HDR... Books and Entertainment
22 C# from getting started to giving up 99.00 100 Give up quickly! Books and Entertainment
30 Ding Ding Ding Ding 123 100.00 100 dsdas Household appliances
31 Ding Ding Ding Ding 5678 100.00 150 dsadsa Books and Entertainment

Adding, deleting and modifying methods (list one)

string pName = "996";
int categoryId = 3;
decimal pPrice = 18.88M;
int pStock = 100;
string pDesc = "2020注定不平凡 2020-1024=996";
string addSql = $"insert into product values('{pName}',{categoryId},{pPrice},{pStock},'{pDesc}')";
int row = DBHelper.ExecuteNonQuery(addSql);
Console.WriteLine($"执行成功,添加成功{row}条数据!");

result
The execution is successful, and 1 data is added successfully!
The database also successfully added a piece of data

Product Number product name Commodity price Commodity stocks product description Product category
1 65-inch Super TV 2599.00 100 4K Ultra Clear HDR123456 Clothing and shoes
2 Drum washing machine 1999.00 50 Fully automatic 10 kg frequency conversion... Household appliances
3 Autumn middle-aged long sleeve T-shirt 159.00 100 Lapel men's autumn base coat... Clothing and shoes
4 Unisex couple baseball cap 298.00 50 The giao language of the peaked cap... Clothing and shoes
5 User Experience Guide: From Methodology to Product Design Practice 98.00 100 The three designers of BAT... Books and Entertainment
6 Knowledge Graph: Methods, Practice and Application 81.00 100 4K ultra-clear HDR... Books and Entertainment
22 C# from getting started to giving up 99.00 100 Give up quickly! Books and Entertainment
30 Ding Ding Ding Ding 123 100.00 100 dsdas Household appliances
31 Ding Ding Ding Ding 5678 100.00 150 dsadsa Books and Entertainment
38 996 18.88 100 2020 is destined to be extraordinary 2020-1024=996 Books and Entertainment

Stored procedures (four of directory one)

1.getProByName

const string procName = "getProByName";
//返回datatable结果集
SqlParameter[] param = new SqlParameter[]
{
    
    
    DBHelper.CreateInput("@name","滚筒洗衣机")
};
var temp = DBHelper.ExecuteProcedureQuery(procName, param);
foreach (DataRow item in temp.Rows)
{
    
    
    Console.WriteLine($"{item["pId"]}\t{item["pName"]}\t{item["pPrice"]}\t{item["pStock"]}\t{item["pDesc"]}\t{item["cName"]}");
}

result

Product Number product name Commodity price Commodity stocks product description Product category
2 Drum washing machine 1999.00 50 Fully automatic 10 kg frequency conversion... Household appliances

2.getProNum

const string outProcName = "getProNum";
//输出参数
SqlParameter[] outputParams = new SqlParameter[]
{
    
    
    DBHelper.CreateOutput("@num",SqlDbType.Int)                
};
var res = DBHelper.ExecuteProcedure(outProcName, outputParams);
Console.WriteLine(res["@num"].Value);

result
There are currently 10 pieces of data in the table
3.getResult

const string returnProcName = "getResult";
//return结果
SqlParameter[] returnParams = new SqlParameter[]
{
    
    
   	DBHelper.CreateReturn(SqlDbType.Int)
};
var data = DBHelper.ExecuteProcedure(returnProcName, returnParams);
Console.WriteLine(data["@ReturnValue"].Value);

result
666
4.getResultAndNum

const string outAndReturnProcName = "getResultAndNum";
//输出参数 + return 结果
SqlParameter[] lastParms = new SqlParameter[]
{
    
    
    
    DBHelper.CreateOutput("@num",SqlDbType.Int),
    DBHelper.CreateReturn(SqlDbType.Int)
};
var last = DBHelper.ExecuteProcedure(outAndReturnProcName, lastParms);
Console.WriteLine(last["@num"].Value+"\r\n"+last["@ReturnValue"].Value);

result
10
10

to sum up

Wuhu took off, and the DBHelper case of ADO.NET connecting to SQL Server is over. Don’t spray if you don’t like it, thank you.

Guess you like

Origin blog.csdn.net/MyLYuchun/article/details/109240541