主鍵表category cId 與外來鍵表 product categoryId相關聯
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
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
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
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
1.config檔案設定
<connectionStrings>
<add name="constr" connectionString="server=.;database=productdb;uid=sa;pwd=scce;"/>
</connectionStrings>
2.通過ConfigurationManager獲取config檔案中的連線字串
ConfigurationManager需要在參照---->新增參照---->程式集中新增System.Configuration參照
private static string constr = ConfigurationManager.ConnectionStrings["constr"].ConnectionString;
//查詢
//返回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;
}
//增刪改
//返回影響行數
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;
}
先定義生成儲存過程引數的方法
1.輸出引數
/// <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.輸出引數
/// <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值
/// <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
};
}
定義執行儲存過程的方法
1.執行查詢的儲存過程
/// <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.執行其他儲存過程
/// <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);
}
return dict;
}
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"]}");
}
結果
商品編號 | 商品名稱 | 商品價格 | 商品庫存 | 商品描述 | 商品類別 |
---|---|---|---|---|---|
1 | 65英寸超級電視 | 2599.00 | 100 | 4K超清HDR123456 | 服裝鞋帽 |
2 | 滾筒洗衣機 | 1999.00 | 50 | 全自動 10公斤變頻…… | 家用電器 |
3 | 秋季中年長袖T恤 | 159.00 | 100 | 翻領男裝秋季打底服…… | 服裝鞋帽 |
4 | 男女通用情侶款棒球帽 | 298.00 | 50 | 鴨舌帽之giao語…… | 服裝鞋帽 |
5 | 使用者體驗指南:從方法論到產品設計實踐 | 98.00 | 100 | BAT三位設計師…… | 圖書文娛 |
6 | 知識圖譜:方法、實踐與應用 | 81.00 | 100 | 4K超清HDR…… | 圖書文娛 |
22 | C#從入門到放棄 | 99.00 | 100 | 快點放棄吧! | 圖書文娛 |
30 | 頂頂頂頂123 | 100.00 | 100 | dsdas | 家用電器 |
31 | 頂頂頂頂5678 | 100.00 | 150 | dsadsa | 圖書文娛 |
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}條資料!");
結果
執行成功,新增成功1條資料!
資料庫也成功新增一條資料
商品編號 | 商品名稱 | 商品價格 | 商品庫存 | 商品描述 | 商品類別 |
---|---|---|---|---|---|
1 | 65英寸超級電視 | 2599.00 | 100 | 4K超清HDR123456 | 服裝鞋帽 |
2 | 滾筒洗衣機 | 1999.00 | 50 | 全自動 10公斤變頻…… | 家用電器 |
3 | 秋季中年長袖T恤 | 159.00 | 100 | 翻領男裝秋季打底服…… | 服裝鞋帽 |
4 | 男女通用情侶款棒球帽 | 298.00 | 50 | 鴨舌帽之giao語…… | 服裝鞋帽 |
5 | 使用者體驗指南:從方法論到產品設計實踐 | 98.00 | 100 | BAT三位設計師…… | 圖書文娛 |
6 | 知識圖譜:方法、實踐與應用 | 81.00 | 100 | 4K超清HDR…… | 圖書文娛 |
22 | C#從入門到放棄 | 99.00 | 100 | 快點放棄吧! | 圖書文娛 |
30 | 頂頂頂頂123 | 100.00 | 100 | dsdas | 家用電器 |
31 | 頂頂頂頂5678 | 100.00 | 150 | dsadsa | 圖書文娛 |
38 | 996 | 18.88 | 100 | 2020註定不平凡 2020-1024=996 | 圖書文娛 |
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"]}");
}
結果
商品編號 | 商品名稱 | 商品價格 | 商品庫存 | 商品描述 | 商品類別 |
---|---|---|---|---|---|
2 | 滾筒洗衣機 | 1999.00 | 50 | 全自動 10公斤變頻…… | 家用電器 |
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);
結果
表內目前一共有10條資料
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);
結果
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);
結果
10
10
蕪湖起飛,ADO.NET連線SQL Server的DBHelper案例就完了,不喜勿噴,謝謝。