Go Premium for a chance to win a PS4. Enter to Win

x
?
Solved

How to read value from SQL COUNT?

Posted on 2008-06-16
14
Medium Priority
?
1,736 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
Concerto Cloud for Software Providers & ISVs

Can Concerto Cloud Services help you focus on evolving your application offerings, while delivering the best cloud experience to your customers? From DevOps to revenue models and customer support, the answer is yes!

Learn how Concerto can help you.

 

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 1000 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

How to Use the Help Bell

Need to boost the visibility of your question for solutions? Use the Experts Exchange Help Bell to confirm priority levels and contact subject-matter experts for question attention.  Check out this how-to article for more information.

Question has a verified solution.

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

Sometimes in DotNetNuke module development you want to swap controls within the same module definition.  In doing this DNN (somewhat annoyingly) swaps the Skin and Container definitions to the default admin selections.  To get around this you need t…
It was really hard time for me to get the understanding of Delegates in C#. I went through many websites and articles but I found them very clumsy. After going through those sites, I noted down the points in a easy way so here I am sharing that unde…
Video by: ITPro.TV
In this episode Don builds upon the troubleshooting techniques by demonstrating how to properly monitor a vSphere deployment to detect problems before they occur. He begins the show using tools found within the vSphere suite as ends the show demonst…
We’ve all felt that sense of false security before—locking down external access to a database or component and feeling like we’ve done all we need to do to secure company data. But that feeling is fleeting. Attacks these days can happen in many w…
Suggested Courses

916 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