473,657 Members | 2,576 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

C# Retrieve COUNT from SQL Query - What am I doing wrong?

Here is what I have:

private int NationalCount()
{
Int32 numRecords = 0;
using (SqlConnection dataConnection = new
SqlConnection(G lobalVars.sqlCo nnString))
{
SqlCommand dataCommand = new SqlCommand();
dataCommand.Com mandText = ("SELECT Count(T1.Report Date) FROM
from ScoutReportsNFS T1 WHERE (guidPlayerPers onID = '" + strCurrentPlaye rID +
"') RETURN COUNT(*)");
try
{
dataConnection. Open();
dataCommand.Con nection = dataConnection;
numRecords = (Int32)dataComm and.ExecuteScal ar();
}
catch (Exception errLog) {
MessageBox.Show (Convert.ToStri ng(errLog)); }
finally { if (dataConnection .State == ConnectionState .Open)
{ dataConnection. Close(); } }
}
return numRecords;
}

It just gives me an error. I believe all my problems are related
specifically to the query. What the heck am I doing wrong??? Thanks guys...
Jul 14 '08 #1
4 6195

"Todd Jaspers" <To*********@di scussions.micro soft.comwrote in message
news:CA******** *************** ***********@mic rosoft.com...
Here is what I have:

private int NationalCount()
{
Int32 numRecords = 0;
using (SqlConnection dataConnection = new
SqlConnection(G lobalVars.sqlCo nnString))
{
SqlCommand dataCommand = new SqlCommand();
dataCommand.Com mandText = ("SELECT Count(T1.Report Date)
FROM
from ScoutReportsNFS T1 WHERE (guidPlayerPers onID = '" +
strCurrentPlaye rID +
"') RETURN COUNT(*)");
try
{
dataConnection. Open();
dataCommand.Con nection = dataConnection;
numRecords = (Int32)dataComm and.ExecuteScal ar();
}
catch (Exception errLog) {
MessageBox.Show (Convert.ToStri ng(errLog)); }
finally { if (dataConnection .State == ConnectionState .Open)
{ dataConnection. Close(); } }
}
return numRecords;
}

It just gives me an error. I believe all my problems are related
specifically to the query. What the heck am I doing wrong??? Thanks
guys...

Your query is a little strange. You only need to do "Select Count(...) From
....". You don't have to add "Return Count(*)".
Jul 14 '08 #2
Ok, I figured it out:
Int32 numRecords = 0;
using (SqlConnection dataConnection = new
SqlConnection(G lobalVars.sqlCo nnString))
{
SqlCommand dataCommand = new SqlCommand();
dataCommand.Com mandText = ("SELECT Count(T1.Report Date) as
numRecords FROM ScoutReportsNFS T1 WHERE (guidPlayerPers onID = '" +
strCurrentPlaye rID + "')");
try
{
dataConnection. Open();
dataCommand.Con nection = dataConnection;
SqlDataReader dataReader = dataCommand.Exe cuteReader();
while (dataReader.Rea d())
{
if (dataReader["numRecords "].ToString() != null) {
numRecords = Convert.ToInt32 ((dataReader["numRecords "].ToString())); }
}
//numRecords = (Int32)dataComm and.ExecuteScal ar();
}
catch (Exception errLog) {
MessageBox.Show (Convert.ToStri ng(errLog)); }
finally { if (dataConnection .State == ConnectionState .Open)
{ dataConnection. Close(); } }
}
return numRecords;

Jul 14 '08 #3
Todd Jaspers wrote:
Here is what I have:

private int NationalCount()
{
Int32 numRecords = 0;
using (SqlConnection dataConnection = new
SqlConnection(G lobalVars.sqlCo nnString))
{
SqlCommand dataCommand = new SqlCommand();
dataCommand.Com mandText = ("SELECT Count(T1.Report Date) FROM
from ScoutReportsNFS T1 WHERE (guidPlayerPers onID = '" + strCurrentPlaye rID +
"') RETURN COUNT(*)");
try
{
dataConnection. Open();
dataCommand.Con nection = dataConnection;
numRecords = (Int32)dataComm and.ExecuteScal ar();
}
catch (Exception errLog) {
MessageBox.Show (Convert.ToStri ng(errLog)); }
finally { if (dataConnection .State == ConnectionState .Open)
{ dataConnection. Close(); } }
}
return numRecords;
}

It just gives me an error. I believe all my problems are related
specifically to the query. What the heck am I doing wrong??? Thanks guys...
Leave out "RETURN COUNT(*)". RETURN statements are only supported from
stored procedures and user-defined functions. .ExecuteScalar( ) will take the
first column of the first row of the first result set of your query and
return that as the result, so no further action on your part is necessary.
Your query also contains a syntax error in the form of a duplicate "from".

Also, you do not need the "finally" block, as closing the connection will be
taken care of when the using block exits. You *should* wrap the SqlCommand
in a using, though, and you *should* use strongly-typed parameters, not
textual substitution, to pass values. So just make it

private int NationalCount() {
using (SqlConnection dataConnection = new
SqlConnection(G lobalVars.sqlCo nnString)) {
dataConnection. Open();
using (SqlCommand dataCommand = dataConnection. CreateCommand() ) {
dataCommand.Com mandText = "SELECT Count(T1.Report Date) FROM
ScoutReportsNFS T1 WHERE guidPlayerPerso nID = @playerID";
dataCommand.Par ameters.AddWith Value("@playerI D", new
Guid(strCurrent PlayerID));
return (int) dataCommand.Exe cuteScalar();
}
}
}

There's no point to catching an exception here to show in a message box;
this isn't dealing with the problem. If you need this, put it in a function
on a higher level.

--
J.
Jul 14 '08 #4
Todd Jaspers wrote:
Here is what I have:

private int NationalCount()
{
Int32 numRecords = 0;
using (SqlConnection dataConnection = new
SqlConnection(G lobalVars.sqlCo nnString))
{
SqlCommand dataCommand = new SqlCommand();
dataCommand.Com mandText = ("SELECT Count(T1.Report Date) FROM
from ScoutReportsNFS T1 WHERE (guidPlayerPers onID = '" + strCurrentPlaye rID +
"') RETURN COUNT(*)");
try
{
dataConnection. Open();
dataCommand.Con nection = dataConnection;
numRecords = (Int32)dataComm and.ExecuteScal ar();
}
catch (Exception errLog) {
MessageBox.Show (Convert.ToStri ng(errLog)); }
finally { if (dataConnection .State == ConnectionState .Open)
{ dataConnection. Close(); } }
}
return numRecords;
}

It just gives me an error. I believe all my problems are related
specifically to the query. What the heck am I doing wrong??? Thanks guys...
In addition to what has been said here, I'd like to add that my
strCurrentPlaye rID is "foo');DROP TABLE ScoutReportsNFS ;--"

Alun Harford
Jul 14 '08 #5

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

2
3087
by: Paxton | last post by:
Hi, I'm trying to display the total page views per page within a given date range, but the correct SQL is seemingly beyond me. I get the correct result with a straightforward Group By and Count clause eg SELECT DISTINCT tblPageViews.PageVisited, Count(tblPageViews.PageVisited) AS CountOfPageVisited FROM tblPageViews GROUP BY tblPageViews.PageVisited;
3
9289
by: thomasp | last post by:
I am trying to get a record count of a PHP query on a MS Acess database using ODBC with a DSN for MS ACCESS connection. I got this code from the PHP manual user notes. It seems to return the correct recount if the count is greater than 0. It the count is 0 it returns the value of the $transid variable in the code. Can someone tell me what I am doing wrong? I need something that returns 0 if not records are found and an accurate count...
6
11492
by: Nicolae Fieraru | last post by:
Hi All, I have a query, Select Count(BoolField) from tblMyTable, Where BoolField = true. If I run the query by itself, it returns the number of true records I want to use the result of that query in my VBA code, like this: If (result of the query > 0) then do something
4
1688
by: m_houllier | last post by:
STUDENT TABLE StudentReference Student Name etc ATTENDANCE TABLE AttendanceID CourseID StudentReference
4
5642
by: max | last post by:
I am beginning to learn sql and need some help. I have a table of customers with their addresses. Let's say I want to run a query returning the number of customers whose last name is "Smith" by state. If I use the following: SELECT customers.state, Count(*) AS FROM customers
13
3422
by: kev | last post by:
Hi all, I have created a database for equipments. I have a form to register the equipment meaning filling in all the particulars (ID, serial, type, location etc). I have two buttons at the end of the form which is submit and cancel. After i have clicked submit, the information is stored directly into my corresponding database table. My problem here is i need to retrieve back the information submitted to display all the data that the...
4
3165
by: Simon Gare | last post by:
Hi all, I am trying to retrieve a count of booking entries made 30 days ago, below is the end of the query I am having problems with. dbo.booking_form.TimeOfBooking = DATEADD(day, -30, GetDate()) GROUP BY dbo.booking_form.TimeOfBooking") When I use the = sign the error reads
5
2496
by: Genalube | last post by:
I am trying to count the number of owners that show up in a query (conveyQuery). The query will produce a column OwnName that will contain names like John Smith, Mike Jones, Frank Vaugn. Each of these names may show up several times and the sorting is such that all the items that person owns will group together. There is a field callled SubParcelNo that has an ID that defines what the owner actually owns. When the query is run, it will return...
2
1670
by: John | last post by:
I am having trouble getting this code to work, and was wondering if someone could tell me what I am doing wrong. -------------------------------------- CODE-------------------------------------- if (isset($_POST)) { require_once("database.php"); $appt_date = $_POST . '/' . $_POST . '/' . $_POST;
0
8732
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
8503
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
8605
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
7324
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
6163
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
4302
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
2726
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
2
1953
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
2
1611
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.