SqlDataReader behaving differently between projects
My project is a Windows Service, and I was having trouble returning values
from my database so I separated the bit of code out into a Console
Application to make for easier debugging but the code that doesn't work in
my Service works in the Console Application.
So in my Service I have this class
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();
}
}
Which I am using like
DBHandler dbHandler = new DBHandler();
WriteToClientStream(clientStream, dbHandler.ReadSQL(string.Format("SELECT
PlayerName FROM Player WHERE PlayerName = '{0}'", UserName)) + "\r\n");
sqlResults.HasRows returns false, but the same query returns results in
MSSQL and the test console application
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();
}
}
No comments:
Post a Comment