【发布时间】:2019-01-12 04:24:35
【问题描述】:
我正在努力实现以下目标:
- 从 SQL DB 中获取数据。
将数据传递给具有第三方方法的 PerformStuff 方法 MethodforResponse(检查输入并提供响应)
将响应 (xml) 保存回 SQL DB。
下面是示例代码。性能方面它不好,如果数据库中有 1000,000 条记录,它非常慢。
这样做更好吗?任何想法或提示可以使它变得更好。
请帮忙。
using thirdpartylib;
public class Program
{
static void Main(string[] args)
{
var response = PerformStuff();
Save(response);
}
public class TestRequest
{
public int col1 { get; set; }
public bool col2 { get; set; }
public string col3 { get; set; }
public bool col4 { get; set; }
public string col5 { get; set; }
public bool col6 { get; set; }
public string col7 { get; set; }
}
public class TestResponse
{
public int col1 { get; set; }
public string col2 { get; set; }
public string col3 { get; set; }
public int col4 { get; set; }
}
public TestRequest GetDataId(int id)
{
TestRequest testReq = null;
try
{
SqlCommand cmd = DB.GetSqlCommand("proc_name");
cmd.AddInSqlParam("@Id", SqlDbType.Int, id);
SqlDataReader dr = new SqlDataReader(DB.GetDataReader(cmd));
while (dr.Read())
{
testReq = new TestRequest();
testReq.col1 = dr.GetInt32("col1");
testReq.col2 = dr.GetBoolean("col2");
testReq.col3 = dr.GetString("col3");
testReq.col4 = dr.GetBoolean("col4");
testReq.col5 = dr.GetString("col5");
testReq.col6 = dr.GetBoolean("col6");
testReq.col7 = dr.GetString("col7");
}
dr.Close();
}
catch (Exception ex)
{
throw;
}
return testReq;
}
public static TestResponse PerformStuff()
{
var response = new TestResponse();
//give ids in list
var ids = thirdpartylib.Methodforid()
foreach (int id in ids)
{
var request = GetDataId(id);
var output = thirdpartylib.MethodforResponse(request);
foreach (var data in output.Elements())
{
response.col4 = Convert.ToInt32(data.Id().Class());
response.col2 = data.Id().Name().ToString();
}
}
//request details
response.col1 = request.col1;
response.col2 = request.col2;
response.col3 = request.col3;
return response;
}
public static void Save(TestResponse response)
{
var Sb = new StringBuilder();
try
{
Sb.Append("<ROOT>");
Sb.Append("<id");
Sb.Append(" col1='" + response.col1 + "'");
Sb.Append(" col2='" + response.col2 + "'");
Sb.Append(" col3='" + response.col3 + "'");
Sb.Append(" col4='" + response.col4 + "'");
Sb.Append("></Id>");
Sb.Append("</ROOT>");
var cmd = DB.GetSqlCommand("saveproc");
cmd.AddInSqlParam("@Data", SqlDbType.VarChar, Sb.ToString());
DB.ExecuteNoQuery(cmd);
}
catch (Exception ex)
{
throw;
}
}
}
谢谢!
【问题讨论】:
-
是否需要将 XML 保存到 DB 中?
-
@DarjanBogdan,其实不是。
-
我建议将记录分成更小的块。存储过程应该只发出一个子集,并为客户端提供某种分页。例如,客户端可以请求特定范围(0 到 500)的记录。在第二个结果集中,该过程可以告诉调用者还剩下多少条记录。
-
我能想到的唯一加速方法是第三方函数是否会在每次调用时接受多个请求对象。否则,您将陷入顺序操作。您可以尝试生成多个工作线程,以便可以同时处理多个记录。
-
通过阅读您的示例代码,您似乎阅读了许多记录而只写了一条。您的 PerformStuff 方法被调用一次并仅返回一个 TestResponse 方法。这是真的吗?