Click here to Skip to main content
15,886,806 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I get this error . in vb.net .. what is the wrong in my code ?

VB
Dim dataset As New DataSet
        Dim adapter As New SqlClient.SqlDataAdapter
        Dim command As New SqlClient.SqlCommand
        Dim cmd = New SqlCommand

        Dim con As New SqlConnection

        Try

            con.Open()
            cmd.Connection = con
            con.ConnectionString = "Data Source=lotus-pc\sqlexpress; Initial Catalog=LawyerSystem; Integrated Security= true "

            cmd.CommandText = "SELECT * FROM [users] WHERE (username='" + TextBox1.Text + "')AND (password='" + TextBox2.Text + "' )   "

            ' cmd.Connection = con
            cmd.ExecuteNonQuery()
            adapter.SelectCommand = command
            '  adapter.SelectCommand.Connection = con
            adapter.Fill(dataset, "0")
            Dim count = dataset.Tables(0).Rows.Count
            If count > 0 Then
                HomePage.Show()
            Else
                MsgBox("uncorrect", MsgBoxStyle.Critical)
            End If



        Catch ex As Exception
            MessageBox.Show("Error while inserting record on table..." & ex.Message, "Insert Records")
        Finally
            con.Close()
        End Try
Posted

1 solution

You get the error because you're trying to open the connection before you've even set the connection string:

VB
con.Open()
cmd.Connection = con
con.ConnectionString = "Data Source=lotus-pc\sqlexpress; Initial Catalog=LawyerSystem; Integrated Security= true"


Change this to:

VB
con.ConnectionString = "Data Source=lotus-pc\sqlexpress; Initial Catalog=LawyerSystem; Integrated Security= true"
con.Open()
cmd.Connection = con


One more thing, this code is very vulnerable to SQL injection:

VB
cmd.CommandText = "SELECT * FROM [users] WHERE (username='" + TextBox1.Text + "')AND (password='" + TextBox2.Text + "' )"


By concatenating unsanitized user input directly into SQL statements you leave yourself wide open. Start parameterizing your queries:

http://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqlparameter.aspx[^]

take a look at:

https://www.owasp.org/index.php/SQL_Injection[^]
 
Share this answer
 
Comments
fjdiewornncalwe 8-Nov-12 11:49am    
+5

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900