How to resolve : 'There is already an open DataReader associated with this Command which must be closed first.' - sql-server

I've been trying to insert data into my sql database but this problem always show up
i've tried redoing it again and the same problem occurs and i'm really stumped right now
Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
Dim conn As SqlConnection = New SqlConnection("Data Source=DESKTOP-OBQR58O\SQLEXPRESS;Initial Catalog=Accounts;Integrated Security=True")
Dim comm As SqlCommand = New SqlCommand("insert into User(username, password)values('" + TextBox1.Text + "', '" + TextBox3.Text + "')", conn)
Dim data As SqlDataAdapter = New SqlDataAdapter(comm)
Dim user = TextBox1.Text
Dim pass = TextBox2.Text
Dim cpass = TextBox3.Text
Dim reader As SqlDataReader
conn.Open()
Dim cmd As SqlCommand = New SqlCommand("select Username from [User] where Username ='" + TextBox1.Text + "'", conn)
conn.Close()
conn.Open()
reader = cmd.ExecuteReader
If user.Trim() = "" Or pass.Trim() = "" Or cpass.Trim() = "" Then
MessageBox.Show("Empty Fields", "Blank Spaces")
ElseIf Not String.Equals(pass, cpass) Then
MessageBox.Show("Passwords do not match", "ERROR")
conn.Close()
ElseIf reader.HasRows Then
MessageBox.Show("Username already exists!", "Error", MessageBoxButtons.OK, MessageBoxIcon.Warning)
TextBox1.Clear()
conn.Close()
reader.Close()
Else
MessageBox.Show("Account created succesfully!", "Success")
Dim table As DataTable = New DataTable()
data.Fill(table) ' this is where the problem occurs.
TextBox1.Clear()
TextBox2.Clear()
TextBox3.Clear()
Dim log As New Login
Me.Close()
log.Show()
conn.Close()
End If
conn.Close()
End Sub
I honestly don't know what to do

You open your reader up at the top:
reader = cmd.ExecuteReader
So, it's open. And then, when you run the Fill command, it conflicts with the open reader!
The simplest fix - although, personally, I would restructure the code a bit, to bring the OpenReader nearer to where it is used - would be to add a Close to your reader right before the Fill.
Else
reader.Close() ' what you would add
MessageBox.Show("Account created succesfully!", "Success")
Dim table As DataTable = New DataTable()
data.Fill(table) ' this is where the problem occurs.
VERY IMPORTANT: If you're not familiar with the concept of "SQL Injection Attacks", read up on them, right away. You should NEVER execute SQL that's been built by constructing a string with unvalidated data from the user. You should pass parameters instead.
After all, what if I typed in the user name of "Irrelevant';DROP TABLE Users;--"? You'd wind up with a SQL Statement that contained "SELECT Username from [Users] WHERE [Username] = 'Irrelevant'; DROP TABLE Users; --'"
And, of course, you should validate the input as well, for things like embedded HTML and script! But that's more complicated than just using SQL Parameters.

Related

Avoid Duplicate record across columns

I Have a code that will determine if a data is already existing. The problem is, it is still adding even already exists.
Already tried some code that will add and not add if data exists
If txtHostname.Text = "" Then
MsgBox("Please fill-up all fields!", MsgBoxStyle.Exclamation, "Inventory!")
Else
Dim theQuery As String = "SELECT * FROM Asset WHERE Monitor1=#Monitor1 AND Monitor2=#Monitor2"
Dim cmd1 As OleDbCommand = New OleDbCommand(theQuery, con)
cmd1.Parameters.AddWithValue("#Monitor1", txtMonitor1.Text)
cmd1.Parameters.AddWithValue("#Monitor2", txtMonitor2.Text)
Using reader As OleDbDataReader = cmd1.ExecuteReader()
If reader.HasRows Then
' User already exists
MsgBox("User Already Exist!", MsgBoxStyle.Exclamation, "Add New User!")
Else
' User does not exist, add them
Dim cmd As OleDbCommand = New OleDbCommand("Insert into Asset ([Monitor1],[Monitor2]) values ('" + txtMonitor1.Text + "','" + txtMonitor2.Text + "')", con2)
cmd.ExecuteNonQuery()
MsgBox("Records Successfully Added!", MsgBoxStyle.Information, "Add New Customer!")
txtMonitor1.Text = ""
txtMonitor2.Text = ""
End If
End Using
con.Close()
End If
It should be, when I search 1 data in column1 it should detect if data is already exists in column1 and column2. Not just in column1.
Well, if you want to search and return the result about whether Fields exist or not , you should not use OledbReader, also I did notice that reader doesn't Read (Even if it is not even correct to use it in this scenario). You could rather use ExecuteScalar and see if Fields exist or not (>0 or <0).
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim CMDText As String = ("SELECT COUNT(*) FROM Asset WHERE Monitor1=#Monitor1 AND Monitor2=#Monitor2")
Dim Found As Integer
If String.IsNullOrEmpty(txtHostname.Text) Then
MsgBox("Please fill-up all fields!", MsgBoxStyle.Exclamation, "Inventory!")
Else
Using CN As New OleDb.OleDbConnection With {.ConnectionString = "CON_STR"},
Cmd1 As New OleDb.OleDbCommand(CMDText, CN)
CN.Open()
With Cmd1.Parameters
.Add("#Monitor1", OleDb.OleDbType.VarChar).Value = txtMonitor1.Text
.Add("#Monitor2", OleDb.OleDbType.VarChar).Value = txtMonitor2.Text
End With
Found = Cmd1.ExecuteScalar()
End Using
If Found > 0 Then
' User already exists
MsgBox("User Already Exist!", MsgBoxStyle.Exclamation, "Add New User!")
Else
Dim CmdText1 As String =
("INSERT INTO Asset (Monitor1,Monitor2) VALUES (#Monitor1 ,#Monitor2)")
Using Cmd As New OleDb.OleDbCommand(CmdText1, CN)
With Cmd.Parameters
.Add("#Monitor1", OleDb.OleDbType.VarChar).Value = txtMonitor1.Text
.Add("#Monitor2", OleDb.OleDbType.VarChar).Value = txtMonitor2.Text
End With
Cmd.ExecuteNonQuery()
' User does not exist, add them
MsgBox("Records Successfully Added!", MsgBoxStyle.Information, "Add New Customer!")
txtMonitor1.Text = String.Empty
txtMonitor2.Text = String.Empty
Cmd.Parameters.Clear()
End Using
End If
End If
End Sub
In my example Code : "CON_STR" = My ConnectionString that I used to test my Code, as you did not provide any.

ExecuteScalar connection property has not not been initialized

When I run this piece of code I get the error:
ExecuteScalar connection property has not not been initialized
I can't seem to find why the connection isn't working.
Code:
Protected Sub btnTrackRepair_Click(sender As Object, e As EventArgs) Handles btnTrackRepair.Click
Using conn As New SqlConnection("Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=|DataDirectory|\ITrepair.mdf;Integrated Security=True")
conn.Open()
Dim cmd As New SqlCommand(conn.ToString)
Dim txtTracking As String
cmd.CommandText = "SELECT Repair_Status FROM Repair WHERE Tracking_Number =" & txtTrack.Text
txtTracking = If(IsDBNull(cmd.ExecuteScalar), "", cmd.ExecuteScalar)
If txtTracking <> "" Then
MsgBox("Record Found!", MsgBoxStyle.Information, "Update")
txtStatus.Text = ""
txtStatus.Text = txtTracking
Else
MsgBox("No Record Found!", MsgBoxStyle.Information, "INFO.")
End If
End Using
End Sub
The code breaks at txtTracking = If(IsDBNull(cmd.ExecuteScalar), "", cmd.ExecuteScalar)
I have looked at other questions regarding this error however most are C# and I'm using VB.NET so I have found it difficult to find a solution.
You are using the SqlCommand constructor which takes only a string. But this is not the connection-string but the text of the query. So you've done it wrong.
Dim cmd As New SqlCommand("SELECT Repair_Status FROM Repair WHERE Tracking_Number = #Tracking_Number", conn)
Apart from that you should really get familiar with parameterized queries. Don't use string concatenation to build your queries to avoid (among other issues) sql-injection attacks.
Here is the complete method:
Protected Sub btnTrackRepair_Click(sender As Object, e As EventArgs)
Dim sqlQuery = "SELECT Repair_Status FROM Repair WHERE Tracking_Number = #Tracking_Number"
Using conn As New SqlConnection("Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=|DataDirectory|\ITrepair.mdf;Integrated Security=True")
conn.Open()
Dim cmd As New SqlCommand(sqlQuery, conn)
cmd.Parameters.Add("#Tracking_Number", SqlDbType.NVarChar).Value = txtTrack.Text
Dim statusObj = cmd.ExecuteScalar()
Dim status = If(statusObj is DBNull.Value, Nothing, DirectCast(statusObj, string))
If not String.IsNullOrEmpty(status) Then
MsgBox("Record Found!", MsgBoxStyle.Information, "Update")
' ... '
Else
MsgBox("No Record Found!", MsgBoxStyle.Information, "INFO.")
End If
End Using
End Sub
If the Tracking_Number is not a varchar/nvarchar but an int(for example) in the database, you should parse it already here and use the correct SqlDbType.

Invalid Column name while column is there

I am trying to create a login window with MDI. It is connected to a SQL Server table test. I have changed the datatypes and deleted and recreated the DB. I have 2 columns: usr and pwd of datatype nvarchar.
Dim connetionString As String
Dim cnn As SqlConnection
connetionString = "Data Source=.;Initial Catalog=test;User ID=sa;Password=sasql"
cnn = New SqlConnection(connetionString)
Dim cmd As SqlCommand
Dim myreader As SqlDataReader
Dim query As String
query = "Select usr From users WHERE (usr =" + TextBox1.Text + " and pwd = " + TextBox2.Text + ")"
cmd = New SqlCommand(query, cnn)
cnn.Open()
myreader = cmd.ExecuteReader()
If myreader.Read() Then
Else
MessageBox.Show("Incorrect username/password !", "LOGIN ERROR", MessageBoxButtons.OK, MessageBoxIcon.Exclamation)
End If
cnn.Close()
Thank you so much.
If you are using Tortuga.Chain, the code would look like this:
Dim ds As New SqlServerDataSource(connetionString)
Dim user = ds.From("users", new With {.usr = TextBox1.Text, .pwd = TextBox2.Text}).ToString.Execute();
If user Is Not Nothing Then
Else
MessageBox.Show("Incorrect username/password !", "LOGIN ERROR", MessageBoxButtons.OK, MessageBoxIcon.Exclamation)
End If
If you want to stick to raw ADO.NET code, you need to use a parameterized query.
Dim connetionString As String
Dim cnn As SqlConnection
connetionString = "Data Source=.;Initial Catalog=test;User ID=sa;Password=sasql"
cnn = New SqlConnection(connetionString)
Dim cmd As SqlCommand
Dim myreader As SqlDataReader
Dim query As String
query = "Select usr From users WHERE (usr = #user and pwd = #pwd )"
cmd = New SqlCommand(query, cnn)
cmd.Parameters.AddWithValue( "#usr", TextBox1.Text)
cmd.Parameters.AddWithValue( "#pwd", TextBox2.Text)
cnn.Open()
myreader = cmd.ExecuteReader()
If myreader.Read() Then
Else
MessageBox.Show("Incorrect username/password !", "LOGIN ERROR", MessageBoxButtons.OK, MessageBoxIcon.Exclamation)
End If
cnn.Close()
Remove the spaces from the value of connectionString.
Your query compares textual data, which is invalid unless the user enters ' at the start and end of the textboxes. This would be syntactically correct:
"Select usr From users WHERE (usr ='" + TextBox1.Text + "' and pwd = '" + TextBox2.Text + "')"
but logically flawed, since the user might attempt to inject malicious SQL into your textboxes. Your application is extremely unsafe. You must protect it against SQL injection and you need to encrypt the password of the user as well.

How to check if a record exists in an Access database

I'm trying a new approach for a project that I'm working on and I'm just starting to learn about Access Databases. I using VB.net and my question is: How do you see if a record exists in the table of the database. I thought I had it understood but that is not the case. I'm creating a login and I want it to check if the Username that they typed in exists before it tries to compare what you typed with what's in the database. I see alot of questions on how to do this...but not for VB.net and MS Access
Here's my code:
Imports System.Data.OleDb
Public Class LoginForm1
Dim provider As String
Dim dataFile As String
Dim connString As String
Public myConnection As OleDbConnection = New OleDbConnection
Public dr As OleDbDataReader
Dim Errors As String
Public Sub AccessAccountDatabase()
provider = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source ="
dataFile = "C:\Users\Richard\Documents\Visual Studio 2010\Projects\CybSol Journal Database\CybSol Journal Database\cgi-bin\Data.mdb"
connString = provider & dataFile
myConnection.ConnectionString = connString
Errors = ""
Try
myConnection.Open()
Dim str As String
str = "SELECT * FROM Accounts WHERE Username='" & UsernameTxt.Text & "' AND Password='" & PasswordTxt.Text & "'"
Dim cmd As OleDbCommand = New OleDbCommand(str, myConnection)
dr = cmd.ExecuteReader
dr.Read()
If UsernameTxt.Text = dr("Username").ToString AndAlso PasswordTxt.Text = dr("Password").ToString Then
Dim Welcome As String = "SELECT * FROM Accounts WHERE Real_Name=" & "Username"
MsgBox("Welcome back " & dr("Real_Name") & "!")
Else
MsgBox("Login Failure")
End If
myConnection.Close()
Catch ex As Exception
MsgBox(ex.ToString)
End Try
End Sub
Private Sub OkayBtn_Click(sender As System.Object, e As System.EventArgs) Handles OkayBtn.Click
AccessAccountDatabase()
End Sub
End Class
So now my question is... How do you get it to check if a record exists in the database, because when you type in the correct information (The correct username and password that exists in the database) it says welcome and all. But when you type in the wrong Username and/or Password it doesn't work. Without the "Try Catch" statement the program just freezes. With the try catch it states this:
System.InvalidOperationException: No data exists for the row/column.
at System.Data.OleDb.OleDbDataReader.DoValueCheck(Int32 ordinal)
at System.Data.OleDb.OleDbDataReader.GetValue(Int32 ordinal)
at System.Data.OleDb.OleDbDataReader.get_Item(String name)
at CybSol_Journal_Database.LoginForm1.AccessAccountDatabase() in c:\users\richard\documents\visual studio 2010\Projects\CybSol Journal Database\CybSol Journal Database\LoginForm1.vb:line 36
Addition information: line 36 is this: If UsernameTxt.Text = dr("Username").ToString AndAlso PasswordTxt.Text = dr("Password").ToString Then
First problem:
PASSWORD is a reserved keyword in Access. You should encapsulate in square brackets:
"SELECT * FROM Accounts WHERE Username='" & UsernameTxt.Text & _
"' AND [Password]='" & PasswordTxt.Text & "'"
Second problem:
NEVER use string concatenation to create sql text. ALWAYS use parameters
str = "SELECT * FROM Accounts WHERE Username=? AND [Password]=?"
Dim cmd As OleDbCommand = New OleDbCommand(str, myConnection)
cmd.Parameters.AddWithValue("user", UserNameTxt.Text)
cmd.Parameters.AddWithValue("pass", PasswordTxt.Text)
dr = cmd.ExecuteReader
Why? look here what could happen if you concatenate strings from user input
Third problem: Test if your command returns rows
If dr.Read() Then
......
End if
I added some Using statements so you don't have to manually close the connections. Also, I parameterized the SQL statement to prevent SQL Injection.
Public Class LoginForm1
Dim provider As String
Dim dataFile As String
Dim connString As String
'Public myConnection As OleDbConnection = New OleDbConnection
'Public dr As OleDbDataReader
Dim Errors As String
Public Sub AccessAccountDatabase()
provider = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source ="
dataFile = "C:\Users\Richard\Documents\Visual Studio 2010\Projects\CybSol Journal Database\CybSol Journal Database\cgi-bin\Data.mdb"
connString = provider & dataFile
myConnection.ConnectionString = connString
Errors = ""
Try
Using myConnection As OleDbConnection = New OleDbConnection(connString)
myConnection.Open()
Dim str As String
str = "SELECT * FROM Accounts WHERE Username=#USER AND [Password]=#PWD "
Using cmd As OleDbCommand = New OleDbCommand(str, myConnection)
cmd.Parameters.AddWithValue("#USER", UsernameTxt.Text)
cmd.Parameters.AddWithValue("#PWD", PasswordTxt.Text)
Using dr As OleDbDataReader = cmd.ExecuteReader
If dr.HasRows Then
dr.Read()
If UsernameTxt.Text = dr("Username").ToString AndAlso PasswordTxt.Text = dr("Password").ToString Then
Dim Welcome As String = "SELECT * FROM Accounts WHERE Real_Name=" & "Username"
MsgBox("Welcome back " & dr("Real_Name") & "!")
Else
MsgBox("Login Failure")
End If
Else
MsgBox("Login Failure")
End If
End Using
End Using
End Using
Catch ex As Exception
MsgBox(ex.ToString)
End Try
End Sub
Private Sub OkayBtn_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles OkayBtn.Click
AccessAccountDatabase()
End Sub
End Class
You're on the right track. The OleDbDataReader.Read returns a boolean indicating whether or not it successfully read an existing row. Therefore, you can check to see if it returned True before trying to read the record. For instance:
If dr.Read() Then
If UsernameTxt.Text = dr("Username").ToString AndAlso PasswordTxt.Text = dr("Password").ToString Then
Dim Welcome As String = "SELECT * FROM Accounts WHERE Real_Name=" & "Username"
MsgBox("Welcome back " & dr("Real_Name") & "!")
Else
MsgBox("Login Failure")
End If
End If
Also, I feel I should at least mention that storing a password in plain text is never a good idea.
You don't have to check for the username and password in your code again since if does not match in the database, no rows will be returned.
You can simply do
dr = cmd.ExecuteReader
If dr.HasRows Then
//it matched
Else
//it didn't match. could not log in
End If
Your approach is below if you still want to keep it but it's not necessary
dr = cmd.ExecuteReader
If dr.HasRows Then
dr.Read()
If UsernameTxt.Text = dr("Username").ToString AndAlso PasswordTxt.Text = dr("Password").ToString Then
Else
End If
End If
Use the Read() method on your DataReader (note that this keeps your connection to the database open and you'll be unable to execute any other commands on the database while your DataReader is still Reading.
If String.Compare(dr("Username").ToString(), UsernameTxt.Text, true) AndAlso String.Compare(dr("Password").ToString(), PasswordTxt.Text.ToString() Then
' The username and password for the record match
' the input from the login form
ProcessLogin()
Else
' Invalid username or password, send an error
End If

Exception causing VB.NET code to not run properly

I am getting an exception when I run the below VB.NET code to validate a user..The exception says that "Incorrect syntax near variable user"
Can anyone tell me where am I going wrong ?
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
If TextBox1.Text.Trim().Length = 0 Or TextBox2.Text.Trim().Length = 0 Then
MsgBox("Enter a user id and password")
Return 'Terminate this method
End If
Dim myconnection As SqlConnection
Dim mycommand As SqlCommand
Dim dr As SqlDataReader
Dim userid = TextBox1.Text
Dim password = TextBox2.Text
Try
myconnection = New SqlConnection("server=PARTH- PC\SQLEXPRESS;uid=sa;pwd=parth;database=fcrit")
myconnection.Open()
mycommand = New SqlCommand("select * from user where [user id]=#userid and [password]=#password", myconnection)
mycommand.Parameters.Add("#userid", SqlDbType.VarChar, 30).Value = userid
mycommand.Parameters.Add("#password", SqlDbType.VarChar, 30).Value = password
'mycommand = New SqlCommand("select * from user where user id='" & TextBox1.Text & "' and password='" & TextBox2.Text & "'", myconnection)
dr = mycommand.ExecuteReader()
If (dr IsNot Nothing) Then
If (dr.Read()) Then
MsgBox("User is authenticated")
Form2.Show()
Else
MsgBox("Please enter correct username and password")
End If
End If
myconnection.Close()
Catch ex As Exception
Throw
Finally
End Try
End Sub
Try changing your SQL to -
"select * from [user] where [user id]=#userid and [password]=#password"
According to this page 'User' is a reserved word
User is a reserved word in SQL Server.
Put brackets around the table name:
mycommand = New SqlCommand("select * from [user] where [user id]=#userid and [password]=#password", myconnection)

Resources