gpt4 book ai didi

c# - 我应该如何合并这两种方法?

转载 作者:太空宇宙 更新时间:2023-11-03 15:36:03 25 4
gpt4 key购买 nike


大家好!
我问过一次熟悉的问题,现在我又被困住了
重构这个的更好方法是什么?
附言。不想将查询作为参数传递,搜索最优雅的解决方案


方法一

public static List<string> GetWinners(Prize prize)
{
List<string> winners = new List<string>();

using (OleDbConnection connection = new OleDbConnection(ConfigurationManager.ConnectionStrings["ForteLotteryDataConnectionString"].ConnectionString))
{
var query = string.Concat(
@"
SELECT Member.IBAN ",
"FROM Member, Summary ",
"WHERE Member.ID = Summary.WinnerID ",
"AND PrizeID = " + prize.ID
);

connection.Open();
OleDbCommand command = new OleDbCommand(query, connection);
OleDbDataReader reader = command.ExecuteReader();

...

connection.Close();
}

return winners;
}


方法二

    public static List<string> GetDoubles(Prize prize)
{
List<string> doubles = new List<string>();

using (OleDbConnection connection = new OleDbConnection(ConfigurationManager.ConnectionStrings["ForteLotteryDataConnectionString"].ConnectionString))
{
var query = string.Concat(
@"
SELECT Member.IBAN ",
"FROM Member, Summary ",
"WHERE Member.ID = Summary.DoubleID ",
"AND PrizeID = " + prize.ID
);

connection.Open();
OleDbCommand command = new OleDbCommand(query, connection);
OleDbDataReader reader = command.ExecuteReader();

...

connection.Close();
}

return doubles;
}

最佳答案

使用 String.Format 并将 propname 作为参数传递:

    public static List<string> GetSomething(string propName, Prize prize)
{
List<string> doubles = new List<string>();

using (OleDbConnection connection = new OleDbConnection(ConfigurationManager.ConnectionStrings["ForteLotteryDataConnectionString"].ConnectionString))
{
var query = string.Format(
@"SELECT Member.IBAN,
FROM Member, Summary,
WHERE Member.ID = Summary.{0},
AND PrizeID = {1}", propName, prize.ID
);

connection.Open();
OleDbCommand command = new OleDbCommand(query, connection);
OleDbDataReader reader = command.ExecuteReader();

...

connection.Close();
}

return doubles;
}

顺便说一句 - 小心 SQLI's - 阅读有关参数化查询的内容。

关于c# - 我应该如何合并这两种方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31847928/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com