use*_*908 -2 c# sql-server asp.net
我试图通过bool响应返回单独查询的值,但我无法正确使用它.除了搜索发现或不发现之外,我没有收到任何错误.Subscriberkey值从另一个类传递到该类.我做出的任何我想到的更改都会破坏代码并添加类似的内容
if (var == null)
{
return true;
}
return SubscriberQuery.LookupSubProfile(querysubscriber);
Run Code Online (Sandbox Code Playgroud)
不起作用.
public static bool LookupSubProfile (SubscriberProfileQuery subscriber)
{
try
{
var connString = "Server = Server\\SQLEXPRESS; initial catalog = Stuff; integrated security = True;";
var query = "SELECT * FROM Subscriber WHERE SubscriberKey = '@SubscriberKey'";
query = query.Replace("@SubscriberKey", subscriber.Subscriberkey);
using (SqlConnection conn = new SqlConnection(connString))
{
conn.Open();
SqlCommand command = new SqlCommand(query, conn);
command.ExecuteNonQuery();
conn.Dispose();
conn.Close();
}
return false;
}
catch
{
return false;
}
Run Code Online (Sandbox Code Playgroud)
让我们尝试解决该代码中存在的所有问题:
ExecuteNonQuery不是a SELECT,因为那只是一个查询.using语句已经调用了Dispose()哪些调用Close(),因此不需要这些调用.bool时,你可以只返回找到的值,null如果没有被发现或抛出异常,如果发生一个.所以:
public static string LookupSubProfile (SubscriberProfileQuery subscriber)
{
try
{
var connString = "Server = Server\\SQLEXPRESS; initial catalog = Stuff; integrated security = True;";
var query = "SELECT * FROM Subscriber WHERE SubscriberKey = @SubscriberKey";
using (SqlConnection conn = new SqlConnection(connString))
{
conn.Open();
using (SqlCommand command = new SqlCommand(query, conn))
{
// 2: add parameters
command.Parameters.Add("SubscriberKey", SqlDataType.VarChar).Value = suscriber.SuscriberKey;
// 1. use ExecuteScalar/ExecuteReader,
// you will need to define what exactly you need here
var result = command.ExecuteScalar();
if (result != null)
{
// 4. return the result
return (string)result;
}
}
// 3. remove unneeded calls
}
// 4. return null if nothing was found
return null;
}
catch
{
// 4: throw the error, log if possible
throw;
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
104 次 |
| 最近记录: |