User Name Password Register
DaniWeb IT Discussion Community
All
What is DaniWeb IT Discussion Community?
You're currently browsing the VB.NET section within the Software Development category of DaniWeb, a massive community of 374,154 software developers, web developers, Internet marketers, and tech gurus who are all enthusiastic about making contacts, networking, and learning from each other. In fact, there are 3,449 IT professionals currently interacting right now! Registration is free, only takes a minute and lets you enjoy all of the interactive features of the site.
Please support our VB.NET advertiser:
Views: 1168 | Replies: 7
Reply
Join Date: Mar 2008
Location: Wales
Posts: 30
Reputation: BluePaper is an unknown quantity at this point 
Rep Power: 1
Solved Threads: 0
BluePaper's Avatar
BluePaper BluePaper is offline Offline
Light Poster

SQL AddWithValue problems

  #1  
Apr 26th, 2008
Hey, I am currently having some problems with VB.net and MSSQL. I'm trying to create an application to learn more about VB.net, I decided to create a simple login system for the application (like the ones they used in distributed applications which have a centeral SQL server). I have come across a problem however.

When I run the program the login box pops up with two text boxes and a login button, one box is the user alias (username) and the other is the password. When the user enters the username and password and clicks login he program checks to see if the user exists using the following SQL statement: "SELECT * FROM tUsers WHERE uAlias = @varAlias AND uPass = @varPass" I then insert the values entered by the user into the SQL query using the following bit of code:

  1. SQLCommand.Parameters.AddWithValue("@varAlias", Trim(txAlias.Text))
  2. SQLCommand.Parameters.AddWithValue("@varPass", Trim(txPassword.Text))

As that's what I've been taught to use, however if the logging in fails the user obviously tries again but on the second go it gives me the following error:

System.Data.SqlClient.SqlException was unhandled
Class=15
ErrorCode=-2146232060
LineNumber=1
Message="The variable name '@varAlias' has already been declared. Variable names must be unique within a query batch or stored procedure."
Number=134
Procedure=""
Server="LAMBDA\SQLEXPRESS"
Source=".Net SqlClient Data Provider"
State=1

(Minus the Strack trace which is huge)

I understand what it is saying, the program is redeclaring the @varAlias variable (and the @varPass if it ever got round to it) but I have no idea how to fix it or where I am going wrong.

I have provided the code for both the application and the external SQL module file I have created. If anyone has any ammendements as well please do say as it's hard learning withotu knowing how proper applications are built.

(My password in the code has been intentionally hid )

  1. 'Import some important things including the database 'wrapper'
  2. Imports Rain.fSQL, System, System.Security.Cryptography, System.Text
  3.  
  4. Public Class Login
  5.  
  6. Dim tmpSuccess As Boolean = False
  7. Dim tmpNoOfTries As Integer
  8. Private Function Login() As Object
  9. If txAlias.Text = "" Or txPassword.Text = "" Then
  10. MsgBox("You left a required field empty!", MsgBoxStyle.Exclamation)
  11. Else
  12. 'Create the SQL string
  13. Dim sqlCheckData As String = "SELECT * FROM tUsers WHERE uAlias = @varAlias AND uPass = @varPass"
  14. 'Encode the password
  15. 'Add the username and password into the sql string
  16. SQLCommand.Parameters.AddWithValue("@varAlias", Trim(txAlias.Text))
  17. SQLCommand.Parameters.AddWithValue("@varPass", Trim(txPassword.Text))
  18. 'Create the SQL connection
  19. fSQL.SQLConnectionCreate()
  20. SqlCommand.Connection = SqlConnection
  21. 'Add the SQL
  22. SqlCommand.CommandText = sqlCheckData
  23. 'Execute the query
  24. SqlCommand.ExecuteNonQuery()
  25. 'Create a data reader
  26. SQLData = SqlCommand.ExecuteReader
  27. 'If any data is found then the username exists
  28. If SQLData.Read() Then
  29. tmpSuccess = True
  30. Else
  31. tmpSuccess = False
  32. End If
  33. fSQL.SQLConnectionClose()
  34. End If
  35. Return tmpSuccess
  36. End Function
  37.  
  38. Private Sub btClose_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btClose.Click
  39. Me.Close()
  40. End Sub
  41.  
  42. Private Sub btLogin_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btLogin.Click
  43. Login()
  44. If tmpSuccess = True Then
  45. btLogin.Enabled = False
  46. MainApp.Show()
  47. Me.Close()
  48. End If
  49. If tmpSuccess = False Then
  50. tmpNoOfTries += 1
  51. MsgBox("Logging in failed, please try again. You have had " & tmpNoOfTries & " of 5 goes", MsgBoxStyle.Exclamation)
  52. End If
  53. If tmpNoOfTries >= 5 Then
  54. btLogin.Enabled = False
  55. lbWarning.Text = "Too many failed attempts!"
  56. End If
  57. End Sub
  58. End Class

  1. Imports System.Data, System.Data.SqlClient
  2. Module fSQL
  3. 'SQL connection variables
  4. Public SQLConnection As New SqlConnection()
  5. Public SQLCommand As New SqlCommand()
  6. Public SQLData As SqlDataReader
  7. 'SQL connection functions
  8. 'Function used for creating the database connection
  9. Public Function SQLConnectionCreate() As Object
  10. If SQLConnection.State = ConnectionState.Closed Then
  11. 'Create the Connection String
  12. Dim SQLConnectionString As String = "Data Source=LAMBDA\SQLEXPRESS;Initial Catalog=Rain;User ID=Skyrail;Password=*******"
  13. 'Set the connection string into the SQL connection
  14. SQLConnection.ConnectionString = SQLConnectionString
  15. 'Open up the connection
  16. SQLConnection.Open()
  17. End If
  18. 'Return the connection status
  19. Return SQLConnection
  20. End Function
  21. 'Function used for closing the database connection
  22. Public Function SQLConnectionClose() As Object
  23. If SQLConnection.State = ConnectionState.Open Then
  24. 'Close the connection
  25. SQLConnection.Close()
  26. End If
  27. Return SQLConnection
  28. End Function
  29. End Module
Stone In Focus - Caffeine Group - CoffeePHP - Open Notes - Onyx - Redpoint Network - Espresso
AddThis Social Bookmark Button
Reply With Quote  
Join Date: Mar 2008
Location: Wales
Posts: 30
Reputation: BluePaper is an unknown quantity at this point 
Rep Power: 1
Solved Threads: 0
BluePaper's Avatar
BluePaper BluePaper is offline Offline
Light Poster

Re: SQL AddWithValue problems

  #2  
Apr 30th, 2008
Can anyone help as this is quite an annoying problem and it would be nice if it could be solved
Stone In Focus - Caffeine Group - CoffeePHP - Open Notes - Onyx - Redpoint Network - Espresso
Reply With Quote  
Join Date: Apr 2008
Posts: 9
Reputation: bcasp is an unknown quantity at this point 
Rep Power: 0
Solved Threads: 2
bcasp bcasp is offline Offline
Newbie Poster

Re: SQL AddWithValue problems

  #3  
Apr 30th, 2008
What version of .NET are you using?

If you have the System.Data.SqlClient (or even System.Data.OleDb) library available, it's actually really easy to do what you're trying to do. I can put up some sample code if you can get to that library.
Reply With Quote  
Join Date: Mar 2008
Location: Wales
Posts: 30
Reputation: BluePaper is an unknown quantity at this point 
Rep Power: 1
Solved Threads: 0
BluePaper's Avatar
BluePaper BluePaper is offline Offline
Light Poster

Re: SQL AddWithValue problems

  #4  
Apr 30th, 2008
I believe I'm working with .NET 3.5, maybe 3.0, it's definately >=3.0 thanks for your time
Stone In Focus - Caffeine Group - CoffeePHP - Open Notes - Onyx - Redpoint Network - Espresso
Reply With Quote  
Join Date: Apr 2008
Posts: 9
Reputation: bcasp is an unknown quantity at this point 
Rep Power: 0
Solved Threads: 2
bcasp bcasp is offline Offline
Newbie Poster

Re: SQL AddWithValue problems

  #5  
Apr 30th, 2008
The first piece of code you would need is a way to execute the queries. The following is a simple method that just takes a SqlCommand and returns a DataSet with the results.

  1. Private Function ExecuteQuery(ByVal cmd As SqlCommand) As DataSet
  2. Dim dbConnection As New SqlConnection(connectionString)
  3.  
  4. cmd.Connection = dbConnection
  5.  
  6. Dim dbAdapter As New SqlDataAdapter()
  7. dbAdapter.SelectCommand = cmd
  8.  
  9. Dim resultSet As New DataSet()
  10.  
  11. dbConnection.Open()
  12. Try
  13. dbAdapter.Fill(resultSet)
  14. Finally
  15. dbConnection.Close()
  16. End Try
  17.  
  18. Return resultSet
  19. End Function

For the actual command, it's pretty simple.

  1. Dim cmd As New SqlCommand()
  2. cmd.CommandType = CommandType.Text
  3. cmd.CommandText = "SELECT column_name FROM table_name WHERE column_name = @inputParam;"
  4.  
  5. cmd.Parameters.AddWithValue("@inputParam", value)
  6.  
  7. Dim results As New DataSet
  8. results = ExecuteQuery(cmd)

You can then go through the data set to get the information you need. I think this approach makes the code a little easier to read.

You need to import System.Data and System.Data.SqlClient for this to work.
Reply With Quote  
Join Date: Apr 2008
Posts: 9
Reputation: bcasp is an unknown quantity at this point 
Rep Power: 0
Solved Threads: 2
bcasp bcasp is offline Offline
Newbie Poster

Re: SQL AddWithValue problems

  #6  
Apr 30th, 2008
Let me know if you try that and anything is deprecated. I originally used it in .NET 2.0.
Reply With Quote  
Join Date: Mar 2008
Location: Wales
Posts: 30
Reputation: BluePaper is an unknown quantity at this point 
Rep Power: 1
Solved Threads: 0
BluePaper's Avatar
BluePaper BluePaper is offline Offline
Light Poster

Re: SQL AddWithValue problems

  #7  
Apr 30th, 2008
Ok so I've taken it, ripped it a part and glued it back together to fit my needs (see code below) now how can I go through the data/check that the row was found, is there a simple tutorial on datasets, adapters and such seeing as I'm used to coming from PHP & MySQL which is an entirely different ball game altogether.

Here's the code I've changed (will it still work? As I've said I don't know it too well and I'm learning on the go):

  1.  
  2. Dim sqlCmd As New SqlCommand()
  3. sqlCmd.CommandType = CommandType.Text
  4. sqlCmd.CommandText = "SELECT * FROM tUsers WHERE uAlias = @varAlias AND uPass = @varPass;"
  5. sqlCmd.Parameters.AddWithValue("@varAlias", txAlias.Text)
  6. sqlCmd.Parameters.AddWithValue("@varPass", varPassword)
  7.  
  8. Dim sqlCmdResults As New DataSet
  9. sqlCmdResults = sqlQuery(sqlCmd)

  1. Public Function sqlQuery(ByVal dbSqlCommand As SqlCommand) As DataSet
  2.  
  3. 'Set the connection string
  4. Dim dbConnectionString As String = "Data Source=LAMBDA\SQLEXPRESS;Initial Catalog=Rain;User ID=Skyrail;Password=*****"
  5. 'Create a database connection function
  6. Dim dbConnection As New SqlConnection(dbConnectionString)
  7. 'Set up the database adapter
  8. Dim dbAdapter As New SqlDataAdapter()
  9. 'Create a dataset to put data into
  10. Dim dbResultData As New DataSet()
  11.  
  12. 'Put the connection data into the function
  13. dbSqlCommand.Connection = dbConnection
  14. 'Something to do with the adapter
  15. dbAdapter.SelectCommand = dbSqlCommand
  16. 'Open the connection
  17. dbConnection.Open()
  18.  
  19. 'Try and put data into the adapter
  20. Try
  21. dbAdapter.Fill(dbResultData)
  22. Finally
  23. dbConnection.Close()
  24. End Try
  25.  
  26. Return dbResultData
  27. End Function

Thanks once again, it looks a lot cleaner now and I'm hoping it will work efficiently
Stone In Focus - Caffeine Group - CoffeePHP - Open Notes - Onyx - Redpoint Network - Espresso
Reply With Quote  
Join Date: Apr 2008
Posts: 9
Reputation: bcasp is an unknown quantity at this point 
Rep Power: 0
Solved Threads: 2
bcasp bcasp is offline Offline
Newbie Poster

Re: SQL AddWithValue problems

  #8  
Apr 30th, 2008
If you're simply trying to see if a row was returned, just take your result DataSet and do something like...

if result.Tables[0].Rows.Count = 0 then
'nothing was found
end if

or

if result.Tables[0].Rows.Count > 0 then
'something was found
end if

Just depends on how you need to use it. Hope this helps.
Last edited by bcasp : Apr 30th, 2008 at 4:20 pm.
Reply With Quote  
Reply

Only community members can participate in forum threads. You must register or log in to contribute.

Currently Active Users Viewing This Thread: 1 (0 members and 1 guests)

 

DaniWeb VB.NET Marketplace
Thread Tools Display Modes

Similar Threads
Other Threads in the VB.NET Forum

All times are GMT -4. The time now is 3:29 am.
Forum system based on vBulletin Copyright ©2000 - 2008, Jelsoft Enterprises Ltd.
©2003 - 2008 DaniWeb® LLC