Solved

How to read value from SQL COUNT?

Posted on 2008-06-16
14
1,717 Views
Last Modified: 2008-06-18
Hi Guys,
I'm trying to use SQL COUNT to check the avilability of Username, but I think the way I'm using COUNT is wrong. Please help me. Thanks
Protected Sub submitButton_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles submitButton.Click
        Dim con As New Data.OleDb.OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" & Server.MapPath("..\App_data\GLC.mdb"))
        Dim Counter As String = "SELECT COUNT(Username) FROM Students WHERE Student.Username = '" + UserName.Text.Replace("'", "_") + "'"
        Dim SqlCommand As String = "INSERT INTO Students ( Students.Username, Password, SchoolID, LastName, FirstName, Email ) Values ('" + UserName.Text.Replace("'", "_") + "','" + Password.Text.Replace("'", "_") + "','" + DropDownListSchool.SelectedValue + "','" + LastName.Text.Replace("'", "_") + "','" + FirstName.Text.Replace("'", "_") + "','" + Email.Text.Replace("'", "_") + "')"
        Dim SqlCommandPro As String = "INSERT INTO ProgramsStudents (ProgramsStudents.Username, ProgramsStudents.CourseID) Values ('" + UserName.Text.Replace("'", "_") + "','" + DropDownListProgram.SelectedValue + "')"
 
 
        If Page.IsValid Then
 
 
            con.Open()
            Dim Count As New Data.OleDb.OleDbCommand(Counter, con)
            Count.ExecuteNonQuery()
 
            Dim Mycommand As New Data.OleDb.OleDbCommand(SqlCommand, con)
            Dim Mycommandd As New Data.OleDb.OleDbCommand(SqlCommandPro, con)
 
            If Counter = 0 Then
                Mycommand.ExecuteNonQuery()
                Mycommandd.ExecuteNonQuery()
 
 
            Else : ErrorMessage2.Text = "User Name is Already Exist!"
            End If
 
 
        End If

Open in new window

0
Comment
Question by:Robertyue
  • 8
  • 3
  • 2
  • +1
14 Comments
 
LVL 143

Expert Comment

by:Guy Hengel [angelIII / a3]
ID: 21797358
you execute the SELECT COUNT query, but don't check the proper results..
Protected Sub submitButton_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles submitButton.Click
        Dim con As New Data.OleDb.OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" & Server.MapPath("..\App_data\GLC.mdb"))
        Dim Counter As String = "SELECT COUNT(Username) c FROM Students WHERE Student.Username = '" + UserName.Text.Replace("'", "_") + "'"
        Dim SqlCommand As String = "INSERT INTO Students ( Students.Username, Password, SchoolID, LastName, FirstName, Email ) Values ('" + UserName.Text.Replace("'", "_") + "','" + Password.Text.Replace("'", "_") + "','" + DropDownListSchool.SelectedValue + "','" + LastName.Text.Replace("'", "_") + "','" + FirstName.Text.Replace("'", "_") + "','" + Email.Text.Replace("'", "_") + "')"
        Dim SqlCommandPro As String = "INSERT INTO ProgramsStudents (ProgramsStudents.Username, ProgramsStudents.CourseID) Values ('" + UserName.Text.Replace("'", "_") + "','" + DropDownListProgram.SelectedValue + "')"
 
 
        If Page.IsValid Then
 
 
            con.Open()
            Dim Count As New Data.OleDb.OleDbCommand(Counter, con)
            Dim r As Data.OleDb.OleDbDataReader = Count.ExecuteReader()
 
            Dim Mycommand As New Data.OleDb.OleDbCommand(SqlCommand, con)
            Dim Mycommandd As New Data.OleDb.OleDbCommand(SqlCommandPro, con)
 
            If r("c") = 0 Then
                Mycommand.ExecuteNonQuery()
                Mycommandd.ExecuteNonQuery()
 
 
            Else : ErrorMessage2.Text = "User Name is Already Exist!"
            End If
 
 
        End If

Open in new window

0
 
LVL 41

Expert Comment

by:graye
ID: 21797362
ExecuteScalar should be used when you expect  your SQL statement to return a single value (such as the output of a COUNT(*) operation)

Dim CountValue as integer

CountValue = Cint(Count.ExecuteScalar())
0
 

Author Comment

by:Robertyue
ID: 21797452
angelIII:
There is a error says SELECT Command format is wrong because you put "c" after COUNT(Username)
0
Free Tool: Path Explorer

An intuitive utility to help find the CSS path to UI elements on a webpage. These paths are used frequently in a variety of front-end development and QA automation tasks.

One of a set of tools we're offering as a way of saying thank you for being a part of the community.

 

Author Comment

by:Robertyue
ID: 21797463
graye:
I'm not sure how to add it in my code, could you please modify my code a little bit? thanks
0
 
LVL 41

Expert Comment

by:graye
ID: 21797979

Dim Mycommand As New Data.OleDb.OleDbCommand(SqlCommand, con)
Dim Mycommandd As New Data.OleDb.OleDbCommand(SqlCommandPro, con)
 
Dim CountValue as integer
CountValue = Cint(Count.ExecuteScalar())
 
if CountValue = 0 then
                Mycommand.ExecuteNonQuery()
                Mycommandd.ExecuteNonQuery()
 

Open in new window

0
 

Author Comment

by:Robertyue
ID: 21798080
Thank you, I did and
It says on "CountValue = CInt(Count.ExecuteScalar())" at least one parameter has not value...
Protected Sub submitButton_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles submitButton.Click
        Dim con As New Data.OleDb.OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" & Server.MapPath("..\App_data\GLC.mdb"))
        Dim Counter As String = "SELECT COUNT(Username) FROM Students WHERE Student.Username = '" + UserName.Text.Replace("'", "_") + "'"
        Dim SqlCommand As String = "INSERT INTO Students ( Students.Username, Password, SchoolID, LastName, FirstName, Email ) Values ('" + UserName.Text.Replace("'", "_") + "','" + Password.Text.Replace("'", "_") + "','" + DropDownListSchool.SelectedValue + "','" + LastName.Text.Replace("'", "_") + "','" + FirstName.Text.Replace("'", "_") + "','" + Email.Text.Replace("'", "_") + "')"
        Dim SqlCommandPro As String = "INSERT INTO ProgramsStudents (ProgramsStudents.Username, ProgramsStudents.CourseID) Values ('" + UserName.Text.Replace("'", "_") + "','" + DropDownListProgram.SelectedValue + "')"
 
 
        If Page.IsValid Then
 
 
            con.Open()
            Dim Count As New Data.OleDb.OleDbCommand(Counter, con)
 
            Dim CountValue As Integer
 
            CountValue = CInt(Count.ExecuteScalar())
 
            Dim Mycommand As New Data.OleDb.OleDbCommand(SqlCommand, con)
            Dim Mycommandd As New Data.OleDb.OleDbCommand(SqlCommandPro, con)
 
            If CountValue = 0 Then
                Mycommand.ExecuteNonQuery()
                Mycommandd.ExecuteNonQuery()
 
 
            Else : ErrorMessage2.Text = "User Name is Already Exist!"
            End If
 
 
        End If
 
 
 
 
    End Sub

Open in new window

0
 
LVL 6

Accepted Solution

by:
rafayali earned 250 total points
ID: 21798739
If you are checking for the existence of a user account, then I dont think you need to use count in this case. The reason being that once you execute this query:

  SELECT COUNT(Username) c FROM Students WHERE Student.Username = '" + UserName.Text.Replace("'", "_") + "'
   
Here since you are using the Where Clause on username, only ONE Record would be returned in this case anyway. So why would you want to use the count. Now, why would only 1 record be returned? That is because usernames would be unique. So, instead of issuing two separate queries to check existence of username, do this:

SELECT * from Students Where STudent.username= .....................................

execute this as executescalar() and then check the value.

Also, double check your sql select. Because the above error where it says that at least one parameter value is missing relates directly to an incorrect sql statement.

To check your sql statements, do a response.write on the sql statement to check whether the correct sql statement is generated.

Although, I would recommend that instead of creating the sql in the way that you have, you use sqlparameters like this:

Count.parameters.addwithvalue("@username",username.text)
Then change your sql statement to this:

SELECT * from students where username=@username

So, your code looks like this:



This way you can avoid coding the statement in this manner.


     Dim con As New Data.OleDb.OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" & Server.MapPath("..\App_data\GLC.mdb"))
        Dim Counter As String = "SELECT * FROM STUDENTS WHERE username=@username"
 
 
        Dim SqlCommand As String = "INSERT INTO Students ( Students.Username, Password, SchoolID, LastName, FirstName, Email ) Values ('" + UserName.Text.Replace("'", "_") + "','" + Password.Text.Replace("'", "_") + "','" + DropDownListSchool.SelectedValue + "','" + LastName.Text.Replace("'", "_") + "','" + FirstName.Text.Replace("'", "_") + "','" + Email.Text.Replace("'", "_") + "')"
        Dim SqlCommandPro As String = "INSERT INTO ProgramsStudents (ProgramsStudents.Username, ProgramsStudents.CourseID) Values ('" + UserName.Text.Replace("'", "_") + "','" + DropDownListProgram.SelectedValue + "')"
 
 
        If Page.IsValid Then
 
 
            con.Open()
            Dim Count As New Data.OleDb.OleDbCommand(Counter, con)
count.parameters.addwithvalue("@username",username.text)
 
            Dim CountValue As Integer
             CountValue = CInt(Count.ExecuteScalar())
 
            Dim Mycommand As New Data.OleDb.OleDbCommand(SqlCommand, con)
            Dim Mycommandd As New Data.OleDb.OleDbCommand(SqlCommandPro, con)
 
            If CountValue = 0 Then
                Mycommand.ExecuteNonQuery()
                Mycommandd.ExecuteNonQuery()
 
 
            Else : ErrorMessage2.Text = "User Name is Already Exist!"
            End If
 
 
        End If
 
 
 
 
    End Sub

Open in new window

0
 

Author Comment

by:Robertyue
ID: 21808535
Thank you, but it says my INSERT INTO Command is wrong...
0
 

Author Comment

by:Robertyue
ID: 21808556
CountValue = CInt(Count.ExecuteScalar()) is wrong:
Conversion from string "hao" to type 'Integer' is not valid.
0
 
LVL 6

Expert Comment

by:rafayali
ID: 21810100
Modify the insert statements to include parameters as well. As you can see, we have resolved the first issue here - initially you were receiving error messages on SELECT. So just change your INSERTS to work with parameters as well, OR the hard way is to check your existing sql query manually (or by doing response.write) and checking for missing quotes. I would recommend that you modify it to use parameters - this is also more secure than creating queries like that.
0
 

Author Comment

by:Robertyue
ID: 21817388
Thank you. It's still the same. May be the way I'm adding parameter is wrong...
 Protected Sub submitButton_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles submitButton.Click
       
 
 
        Dim con As New Data.OleDb.OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" & Server.MapPath("..\App_data\GLC.mdb"))
        Dim Counter As String = "SELECT * FROM STUDENTS WHERE username=@username"
 
 
        Dim SqlCommand As String = "INSERT INTO Students ( Username, [Password], SchoolID, LastName, FirstName, Email ) Values (@Username,@Password,@SchoolID,@LastName,@FirstName,@Email)"
        Dim SqlCommandPro As String = "INSERT INTO ProgramsStudents (Username, CourseID) Values (@Username,@CourseID)"
 
 
 
        If Page.IsValid Then
 
 
            con.Open()
            Dim Count As New Data.OleDb.OleDbCommand(Counter, con)
            Count.Parameters.AddWithValue("@username", UserName.Text)
 
            Dim CountValue As Integer
            CountValue = CInt(Count.ExecuteScalar())
 
            Dim Mycommand As New Data.OleDb.OleDbCommand(SqlCommand, con)
            Dim Mycommandd As New Data.OleDb.OleDbCommand(SqlCommandPro, con)
 
            Mycommand.Parameters.AddWithValue("@Username", UserName.Text.Replace("'", "_"))
            Mycommand.Parameters.AddWithValue("@Password", Password.Text.Replace("'", "_"))
            Mycommand.Parameters.AddWithValue("@SchoolID", DropDownListSchool.SelectedValue)
            Mycommand.Parameters.AddWithValue("@LastName", LastName.Text.Replace("'", "_"))
            Mycommand.Parameters.AddWithValue("@FirstName", FirstName.Text.Replace("'", "_"))
            Mycommand.Parameters.AddWithValue("@Email", Email.Text.Replace("'", "_"))
 
            Mycommandd.Parameters.AddWithValue("@Username", UserName.Text.Replace("'", "_"))
            Mycommandd.Parameters.AddWithValue("@CourseID", DropDownListProgram.SelectedValue)
 
 
            If CountValue = 0 Then
                Mycommand.ExecuteNonQuery()
                Mycommandd.ExecuteNonQuery()
 
 
            Else : ErrorMessage2.Text = "User Name is Already Exist!"
            End If
 
 
        End If
 
    End Sub

Open in new window

0
 

Author Comment

by:Robertyue
ID: 21817418
I think there is nothing to do with Insert Command because it works fine without checking username.  May be username is a text field, the data type doesn't match with ExecuteScalar()?
0
 

Author Comment

by:Robertyue
ID: 21817531
it works now! I changed SELECT command to
Dim Counter As String = "SELECT COUNT(Username) FROM STUDENTS WHERE Username=@Username"
I used COUNT.
Thank you so much!
0
 
LVL 6

Expert Comment

by:rafayali
ID: 21817646
What is the exact error message at this point? If it works fine without checking username, then do a response.write(countValue) before the If countvalue=0 block and see what value is being returned. Just comment out all code besides the one that checks for username in database and see what error message is returned, OR what value is returned into countValue after executescalar() is executed.

Also, you also have the option to do this in the database itself by DISALLOWING DUPLICATE VALUES for username. Then, when an INSERT is executed and the system reads a duplicate value, an exception is thrown that can be caught and the error message displayed to the user that reads "USER NAME ALREADY EXISTS. CHOOSE A NEW ONE PLEASE."


Also, Try changing your select statement to this:

select count(*) FROM STUDENTS WHERE username=@username
Here's a sample SELECT code that i wrote on my system.



Dim objComm As New OleDbConnection("provider=microsoft.jet.oledb.4.0;data source=|DataDirectory|\members.mdb")
        Dim myReturn As Integer
        Dim objConn As New OleDbCommand("select count(*) from users where username=@username", objComm)
        objConn.Parameters.AddWithValue("@username", "rafay")

        Using objComm
            objComm.Open()
            myReturn = Convert.ToInt16(objConn.ExecuteScalar())
        End Using

        Response.Write(myReturn)

(Dont be confused by my usage of Objconn and ObjComm variables. They should have been other way round.)
0

Featured Post

Free Tool: Site Down Detector

Helpful to verify reports of your own downtime, or to double check a downed website you are trying to access.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Suggested Solutions

In this Article, I will provide a few tips in problem and solution manner. Opening an ASPX page in Visual studio 2003 is very slow. To make it fast, please do follow below steps:   Open the Solution/Project. Right click the ASPX file to b…
One of the pain points with developing AJAX, JavaScript, JQuery, and other client-side behaviors is that JavaScript doesn’t allow for cross domain request for pulling content. For example, JavaScript code on www.johnchapman.name could not pull conte…

820 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question