Solved

How to read value from SQL COUNT?

Posted on 2008-06-16
14
1,708 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 142

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
 

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
Maximize Your Threat Intelligence Reporting

Reporting is one of the most important and least talked about aspects of a world-class threat intelligence program. Here’s how to do it right.

 

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

What Is Threat Intelligence?

Threat intelligence is often discussed, but rarely understood. Starting with a precise definition, along with clear business goals, is essential.

Join & Write a Comment

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…
In an ASP.NET application, I faced some technical problems. In this article, I list them out and show the solutions that I found.  I hope it will be useful. Problem: After closing a pop-up window, the parent page should be refreshed automaticall…
Excel styles will make formatting consistent and let you apply and change formatting faster. In this tutorial, you'll learn how to use Excel's built-in styles, how to modify styles, and how to create your own. You'll also learn how to use your custo…
You have products, that come in variants and want to set different prices for them? Watch this micro tutorial that describes how to configure prices for Magento super attributes. Assigning simple products to configurable: We assigned simple products…

705 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

Need Help in Real-Time?

Connect with top rated Experts

18 Experts available now in Live!

Get 1:1 Help Now