c#多个SQL选择语句单一方法
本文关键字:单一 方法 语句 选择 多个 SQL | 更新日期: 2023-09-27 18:15:59
我的任务是开发一个控制台应用程序,该应用程序是对DB中几个表的值进行侦察。我有每个值所需的所有查询,并了解值如何交互的逻辑。我面临的挑战是检索和存储这些值的最佳方法。
我已经研究并成功地创建了从单个SQL查询中检索单个值的静态方法,但我很好奇最好的方法:
-
创建多个方法来检索每个值(超过15个不同的选择语句),总结如下(不完整的代码)
static double total1(int arg) { using (SqlConnection connection = new SqlConnection(connectionString)) { connection.Open(); SqlCommand command1 = new SqlCommand(commandText1, connection)); return(response); } } static double total2(int arg) { using (SqlConnection connection = new SqlConnection(connectionString)) { connection.Open(); SqlCommand command2 = new SqlCommand(commandText2, connection)); return(response); } }
-
尝试将所有选择语句组合在一个方法中(我在这里没有成功),总结如下(不完整的代码)
using (SqlConnection connection = new SqlConnection(connectionString)) { connection.Open(); using (SqlCommand command1 = new SqlCommand(commandText1, connection)) { } using (SqlCommand command2 = new SqlCommand(commandText2, connection)) { } // etc }
-
在SQL中创建存储过程并执行它们,并通过c#控制台应用程序传递参数
我认为方法1将对服务器征税,因为它需要连接打开和关闭多次(尽管我不知道这是否像我认为的那样是个大问题)。方法2似乎更合理,尽管我遵循了这里的概念,当我试图获得命令的输出(我使用return)时,我陷入了困境。方法3对我来说似乎更聪明,尽管我仍然处于需要在方法1之间做出选择的位置。2 .执行SP。
我非常感谢这里的建议和指导,我是c#新手,所以当教程没有涵盖这类事情(或者至少我不能正确定义我的问题)时,这是一个陡峭的学习曲线
string query = "SELECT * FROM table1;";
query += "SELECT * FROM table2";
using (SqlConnection con = new SqlConnection(constr))
{
using (SqlCommand cmd = new SqlCommand(query))
{
using (SqlDataAdapter sda = new SqlDataAdapter())
{
cmd.Connection = con;
sda.SelectCommand = cmd;
using (DataSet ds = new DataSet())
{
sda.Fill(ds);
}
}
}
}
我最近看到这个问题仍然在被查看,所以我将为那些刚刚开始开发并遇到类似挑战的人发布解决方案。
最合适的解决方案是创建一个存储过程,将每个唯一参数传递给它,并在对应用程序的单个响应中返回所有相关数据。为此输出定义了自定义模型,并相应地调整了应用程序逻辑。结果是对数据库的单个调用运行时间更长,而不是多个单独的调用。
使用问题中的格式,解决方案是:
c#代码
static NewModel AllTotals(int arg1, int arg2)
{
using (SqlConnection connection = new SqlConnection(connectionString))
{
connection.Open();
var commandText = "TheStoredProcName";
SqlCommand command = new SqlCommand(commandText, connection));
command.CommandType = System.Data.CommandType.StoredProcedure;
Cmd.Parameters.AddWithValue("@arg1", arg1);
Cmd.Parameters.AddWithValue("@arg1", arg2);
using (SqlDataReader dr = Cmd.ExecuteReader())
{
while (dr.Read())
{
var response = new NewModel(){
Value1 = Convert.ToDecimal(dr["value1"]),
Value2 = Convert.ToDecimal(dr["value2"]),
};
return(response);
}
}
}
return null;
}
SQL存储过程
CREATE PROCEDURE [dbo].[TheStoredProcName]
@arg1 int,
@arg2 int
AS
DECLARE @value1 decimal(18,6) = ISNULL((--QUERY TO GET VALUE1),0)
DECLARE @value2 decimal(18,6) = ISNULL((--QUERY TO GET VALUE2),0)
-- select the variables into a result set for the application
SELECT @value1 as [value1], @value2 as [value2]