我的项目是一个 Windows 服务,我在从数据库返回值时遇到问题,所以我将部分代码分离到控制台应用程序中以便于调试,但在我的服务中不起作用的代码在控制台应用程序中工作.
所以在我的服务中,我有这门课
public class DBHandler
{
public string ReadSQL(string sql)
{
try
{
using (SqlConnection DBConnection = new SqlConnection(@"Data Source=***;Initial Catalog=***;Integrated Security=True;User ID=***;Password=***"))
{
DBConnection.Open();
SqlCommand DBCommand = new SqlCommand(sql, DBConnection);
SqlDataReader sqlResults = DBCommand.ExecuteReader();
if (sqlResults.HasRows)
{
while (sqlResults.Read())
{
return sqlResults.GetString(0);
}
}
return sqlResults.HasRows.ToString();
}
}
catch (Exception e)
{
return e.ToString();
}
}
我正在使用的
DBHandler dbHandler = new DBHandler();
WriteToClientStream(clientStream, dbHandler.ReadSQL(string.Format("SELECT PlayerName FROM Player WHERE PlayerName = '{0}'", UserName)) + "\r\n");
sqlResults.HasRows 返回 false,但相同的查询在 SQL Server 和测试控制台应用程序中返回结果
public static void Main(string[] args)
{
Console.WriteLine(ReadSQL(string.Format("SELECT PlayerName FROM Player WHERE PlayerName = '{0}'", "Hex")));
Console.ReadLine();
}
public static string ReadSQL(string sql)
{
try
{
using (SqlConnection DBConnection = new SqlConnection(@"Data Source=***;Initial Xatalog=***;Integrated Security=True;User ID=***;Password=***"))
{
DBConnection.Open();
SqlCommand DBCommand = new SqlCommand(sql, DBConnection);
SqlDataReader sqlResults = DBCommand.ExecuteReader();
if (sqlResults.HasRows)
{
while (sqlResults.Read())
{
return sqlResults.GetString(0);
}
}
return sqlResults.HasRows.ToString();
}
}
catch (Exception e)
{
return e.ToString();
}
}