how validate if record not found on database in vb.net - vb.net

how make sure if record not found when sql query using where not get the result.
i use this source and work for display record if record found, but i don't know how use "if then else" for change the "while"
Sub usercheck()
'Prepare Connection and Query
dbconn = New MySqlConnection("Server=localhost;Database=user_team;Uid=root;Pwd=")
strQuery = "SELECT * " & _
"FROM tb_team_user WHERE user_ip = '" & lip.Text & "'"
SQLCmd = New MySqlCommand(strQuery, dbconn)
'OPEN THE DB AND KICKOFF THE QUERY
dbconn.Open()
DR = SQLCmd.ExecuteReader
While DR.Read
tbteam.Text = DR.Item("user_team")
End While
End Sub

Before your while loop, you can add an if statement to see if there are any rows returned:
If DR.HasRows Then
' There was at least 1 row returned
Else
' There were no rows returned
End If

Related

How do I read HasRow then Update?

Is it possible to read HasRow and then Update ?
This is the code what I have tried so far :
If conn.State = ConnectionState.Closed Then
conn.Open()
End If
Dim sqlcmd As New MySqlCommand("SELECT * FROM tbl_online_attendance where employees_id = '" & lvRealAtt.Items(itms).SubItems(0).Text & "' and in_time = '" & lvRealAtt.Items(itms).SubItems(1).Text & "' ", conn)
Dim dr As MySqlDataReader
dr = sqlcmd.ExecuteReader
If dr.HasRows Then
Dim query As String
query = "UPDATE tbl_online_attendance SET out_time = '" & lvRealAtt.Items(itms).SubItems(2).Text & "' where employees_id = '" & lvRealAtt.Items(itms).SubItems(0).Text & "' and in_time = '" & lvRealAtt.Items(itms).SubItems(1).Text & "' "
sqlcmd.Connection = conn
sqlcmd.CommandText = query
sqlcmd.ExecuteNonQuery() 'It error in this part
Else
End If
But it give's me error saying:
There is already an open DataReader associated with this Connection which must be closed first
Please avoid commenting Use Parameters Your code is Prone to SQL injection attack
You should not have to check connection state if you keep your connections local to the method that they are used. Database objects like connections and commands need to be closed and disposed as soon as possible. Using...End Using blocks take care of this for you even if there is an error. Don't open a connection until directly before the .Execute....
Don't pull down data when you only need Count. .ExecuteScalar returns the first column of the first row of the result set, which in this case, is the Count. If you have a large table you need to look into If Exists which will stop as soon it finds a match whereas Count looks at the whole table.
Always use Parameters. Never concatenate strings to build sql queries to avoid sql injection. I had to guess at the datatypes of the parameters. Check your database to get the actual types and adjust the code accordingly.
Private Sub OPCode(ByVal itms As Integer)
Dim RowCount As Integer
Using conn As New MySqlConnection("Your connection string"),
sqlcmd As New MySqlCommand("SELECT Count(*) FROM tbl_online_attendance where employees_id = #id and in_time = #inTime;", conn)
sqlcmd.Parameters.Add("#id", MySqlDbType.Int32).Value = CInt(lvRealAtt.Items(itms).SubItems(0).Text)
sqlcmd.Parameters.Add("#inTime", MySqlDbType.String).Value = lvRealAtt.Items(itms).SubItems(1).Text
conn.Open()
RowCount = CInt(sqlcmd.ExecuteScalar)
If RowCount > 0 Then
sqlcmd.CommandText = "UPDATE tbl_online_attendance SET out_time = #outTime where employees_id = #id and in_time = #inTime;"
sqlcmd.Parameters.Add("#outTime", MySqlDbType.String).Value = lvRealAtt.Items(itms).SubItems(2).Text
sqlcmd.ExecuteNonQuery()
End If
End Using
End Sub
Every SqlDataReader needs to be closed before you could execute another query.
so i suggest you to separate the sqlreader and the update query, put the reader into a boolean function to check either a row with those parameters exist or not.
Private Function HasRow(ByVal employeeid As Integer, ByVal date as DateTime) As Boolean
HasRow = False
Dim reader As SqlDataReader
'do select query here
'use the if reader.Read if you want to
HasRow = reader.HasRows
reader.Close()
End Function
Call the function before updating, if it's True then proceed the update. Let's say we put it into a Update Sub.
Private Sub Update()
If HasRows(parameters here) Then
'update query here
End If
End Sub

MysqlDataReader.Read stuck on the last record and doesnt EOF

i confused why mySqlDataReader.Read stuck on the last record and doesnt EOF ..
Here's my private function for executeSql :
Private Function executeSQL(ByVal str As String, ByVal connString As String, ByVal returnRecordSet As Boolean) As Object
Dim cmd As Object
Dim objConn As Object
Try
If dbType = 2 Then
cmd = New MySqlCommand
objConn = New MySqlConnection(connString)
Else
cmd = New OleDbCommand
objConn = New OleDbConnection(connString)
End If
'If objConn.State = ConnectionState.Open Then objConn.Close()
objConn.Open()
cmd.Connection = objConn
cmd.CommandType = CommandType.Text
cmd.CommandText = str
If returnRecordSet Then
executeSQL = cmd.ExecuteReader()
executeSQL.Read()
Else
cmd.ExecuteNonQuery()
executeSQL = Nothing
End If
Catch ex As Exception
MsgBox(Err.Description & " #ExecuteSQL", MsgBoxStyle.Critical, "ExecuteSQL")
End Try
End Function
And this is my sub to call it where the error occurs :
Using admsDB As MySqlConnection = New MySqlConnection("server=" & rs("server") & ";uid=" & rs("user") & ";password=" & rs("pwd") & ";port=" & rs("port") & ";database=adms_db;")
admsDB.Open()
connDef.Close()
rs.Close()
'get record on admsdb
Dim logDate As DateTime
Dim str As String
str = "select userid, checktime from adms_db.checkinout in_out where userid not in (select userid " &
"from adms_db.checkinout in_out join (select str_to_date(datetime,'%d/%m/%Y %H:%i:%s') tgl, fid from zsoft_bkd_padang.ta_log) ta " &
"on ta.fid=userid and tgl=checktime)"
Dim rsAdms As MySqlDataReader = executeSQL(str, admsDB.ConnectionString, True)
Dim i As Integer
'This is where the error is, datareader stuck on the last record and doesnt EOF
While rsAdms.HasRows
'i = i + 1
logDate = rsAdms(1)
'save to ta_log
str = "insert into ta_log (fid, Tanggal_Log, jam_Log, Datetime) values ('" & rsAdms(0) & "','" & Format(logDate.Date, "dd/MM/yyyy") & "', '" & logDate.ToString("hh:mm:ss") & "', '" & logDate & "')"
executeSQL(str, oConn.ConnectionString, False)
rsAdms.Read()
End While
'del record on admsdb
str = "truncate table checkinout"
executeSQL(str, admsDB.ConnectionString, False)
End Using
i'm new to vbnet and really have a little knowledge about it,, please help me,, and thank you in advance..
The issue is that you're using the HasRows property as your loop termination expression. The value of that property never changes. Either the reader has rows or it doesn't. It's not a check of whether it has rows left to read, so reading has no effect.
You are supposed to use the Read method as your flag. The data reader begins without a row loaded. Each time you call Read, it will load the next row and return True or, if there are no more rows to read, it returns False.
You normally only use HasRows if you want to do something special when the result set is empty, e.g.
If myDataReader.HasRows Then
'...
Else
MessageBox.Show("No matches found")
End If
If you don't want to treat an empty result set as a special case then simply call Read:
While myDataReader.Read()
Dim firstFieldValue = myDataReader(0)
'...
End While
Note that trying to access any data before calling Read will throw an exception.

Visual basic - Incrementing the score

Private Sub Button4_Click(sender As Object, e As EventArgs) Handles Button4.Click
Dim READER As MySqlDataReader
Dim Query As String
Dim connection As MySqlConnection
Dim COMMAND As MySqlCommand
Dim item As Object
Try
item = InputBox("What is the item?", "InputBox Test", "Type the item here.")
If item = "shoe" Then
Dim connStr As String = ""
Dim connection As New MySqlConnection(connStr)
connection.Open()
Query = "select * from table where username= '" & Login.txtusername.Text & " '"
COMMAND = New MySqlCommand(Query, connection)
READER = COMMAND.ExecuteReader
If (READER.Read() = True) Then
Query = "UPDATE table set noOfItems = noOfItems+1, week1 = 'found' where username= '" & Login.txtusername.Text & "'"
Dim noOfItems As Integer
Dim username As String
noOfItems = READER("noOfItems") + 1
username = READER("username")
MessageBox.Show(username & "- The number of items you now have is: " & noOfGeocaches)
End If
Else
MsgBox("Unlucky, Incorrect item. Please see hints. Your score still remains the same")
End If
Catch ex As Exception
MessageBox.Show("Error")
End Try
I finally got the message box to display! but now my code does not increment in the database, can anybody help me please :D
Thanks in advance
After fixing your typos (space after the login textbox and name of the field retrieved) you are still missing to execute the sql text that updates the database.
Your code could be simplified understanding that an UPDATE query has no effect if the WHERE condition doesn't find anything to update. Moreover keeping an MySqlDataReader open while you try to execute a MySqlCommand will trigger an error in MySql NET connector. (Not possible to use a connection in use by a datareader). We could try to execute both statements in a single call to ExecuteReader separating each command with a semicolon and, of course, using a parameter and not a string concatenation
' Prepare the string for both commands to execute
Query = "UPDATE table set noOfItems = noOfItems+1, " & _
"week1 = 'found' where username= #name; " & _
"SELECT noOfItems FROM table WHERE username = #name"
' You already know the username, don't you?
Dim username = Login.txtusername.Text
' Create the connection and the command inside a using block to
' facilitate closing and disposing of these objects.. exceptions included
Using connection = New MySqlConnection(connStr)
Using COMMAND = New MySqlCommand(Query, connection)
connection.Open()
' Set the parameter value required by both commands.
COMMAND.Parameters.Add("#name", MySqlDbType.VarChar).Value = username
' Again create the reader in a using block
Using READER = COMMAND.ExecuteReader
If READER.Read() Then
Dim noOfItems As Integer
noOfItems = READER("noOfItems")
MessageBox.Show(username & "- The number of items you now have is: " & noOfItems )
End If
End Using
End Using
End Using

Delete SQL Statement

I have an update sql statement that runs perfect to update a record in msaccess via vb.net. Is there anyway to turn it into a delete statement as well? So i have a button to update the record and if i want to Delete the record.
Code for the update:
Dim sqlupdate As String
' Here we use the UPDATE Statement to update the information. To be sure we are
' updating the right record we also use the WHERE clause to be sureno information
' is added or changed in the other records
'sqlupdate = "UPDATE Table1 SET Title=#Title, YearofFilm=#YearofFilm, Description=#Description, Field1=#Field1 WHERE ID='" & TextBox5.Text & "'"
'WHERE YearofFilm='" & TextBox2.Text & "'"
'sqlupdate = "UPDATE Table1 SET Title=#Title, YearofFilm=#YearofFilm, Description=#Description, " & "Field1=#Field1 WHERE ID='" & TextBox5.Text & "'"
sqlupdate = "UPDATE Table1 SET Title=#Title, YearofFilm=#YearofFilm, " & _
"Description=#Description, Field1=#Field1 WHERE ID=#id"
Dim cmd As New OleDbCommand(sqlupdate, con1)
' This assigns the values for our columns in the DataBase.
' To ensure the correct values are written to the correct column
cmd.Parameters.AddWithValue("#Title", TextBox1.Text)
cmd.Parameters.AddWithValue("#YearofFilm", Convert.ToInt32(TextBox2.Text))
cmd.Parameters.AddWithValue("#Description", TextBox3.Text)
cmd.Parameters.AddWithValue("#Field1", TextBox4.Text)
cmd.Parameters.AddWithValue("#ID", Convert.ToInt32(TextBox5.Text))
' This is what actually writes our changes to the DataBase.
' You have to open the connection, execute the commands and
' then close connection.
con1.Open()
cmd.ExecuteNonQuery()
con1.Close()
' This are subs in Module1, to clear all the TextBoxes on the form
' and refresh the DataGridView on the MainForm to show our new records.
ClearTextBox(Me)
Me.Close()
RefreshDGV()
should be something like this
Dim ConnString As String = "yourConnectionString"
Dim SqlString As String = "Delete From Table1 Where ID=#id"
Using conn As New OleDbConnection(ConnString)
Using cmd As New OleDbCommand(SqlString, conn)
cmd.Parameters.AddWithValue("#ID", Convert.ToInt32(TextBox5.Text))
conn.Open()
cmd.ExecuteNonQuery()
conn.Close()
End Using
End Using
Greetings!

SqlDataReader getting rows when no data

This is incredibly urgent, I need to present this application in 3 and a half hours.
My application checks against a data source to see if a value exists in the database and changes values depending on whether or not the value in question was found.
The problem is that I've run the sql query with the value in question in SSMS and no rows were returned, and yet, my DataReader says it has rows.
This means that my application is reporting inaccurately.
Here's my code:
Using conn As New SqlConnection("Data Source=.\SQLEXPRESS; Initial Catalog=Testing; Integrated Security=True;")
Dim cmd As New SqlCommand(sql, conn)
conn.Open()
Dim reader As SqlDataReader = cmd.ExecuteReader
If reader.HasRows Then
Value = True
AcctNumber = reader(1)
End If
reader.Close()
End Using
I've removed code that's not relevant to this post, but what you may want to know is:
Value is Boolean
AcctNumber is a String
As this is an application for work, I'd rather not include the SQL Query. The problem is the reader. If I comment out Value = True, I get the right info, but leaving that out will mean that in a case where Value should be True, it'll report inaccurately as well.
Thanks in advance!
EDIT: Full Source Code:
Case "Business"
' Change the number format to local because that's what it is in the db
If Microsoft.VisualBasic.Left(NumberToCheck, 2) = "27" Then
NumberToCheck = NumberToCheck.Replace(Microsoft.VisualBasic.Left(NumberToCheck, 2), "0")
End If
Dim sql As String = "SELECT a.TelNumber, c.AccountNumber " & _
"FROM TelInfo a " & _
"INNER JOIN Customers b ON a.CustID = b.pkguidId " & _
"INNER JOIN Accounts c ON b.pkguidId = c.CustID " & _
"WHERE a.TelNumber = '" & NumberToCheck & "'"
Using conn As New SqlConnection("Data Source=.\SQLEXPRESS; Initial Catalog=Testing; Persist Security Info=True; " & _
"User Id=JoeSoap; Password=paoseoj;")
Dim cmd As New SqlCommand(sql, conn)
conn.Open()
Dim reader As SqlDataReader = cmd.ExecuteReader
If reader.Read Then
Value = True
AcctNumber = reader(1)
End If
reader.Close()
End Using
On the comments below made before 08/02/10 (mm/dd/yy):
Value is just a boolean that gets returned by the function to indicate that the searched telephone number (NumberToCheck) exists in the database.
So...
Private AcctNumber As String
Dim val As Boolean = False
val = CheckNumber("3235553469")
If val Then
' AcctNumber will have been set by CheckNumber
Label1.Text = AcctNumber
End If
val will only be returned True if the NumberToCheck (in this example 3235553469) exists in the database.
Having copied the value of NumberToCheck into SSMS and testing the query there, I can verify that the query does work as expected.
No, I can't populate a DataSet because of the volume of information in the table (+/- 9.5m rows). Even with the 'WHERE' filter, the query is too heavy on resources and eventually ends in an OutOfMemory Exception which is why I went with a DataReader.
I'm going to try the ExecuteScalar option as suggested as an answer by Darryl now, will update with the results.
Try changing your If statement to
If reader.Read() Then
Value = True
AcctNumber = reader(1)
End If
HasRows exhibits strange behavior in certain situations, so it's better to avoid it altogether.
This does not solve the problem, but it may get you through your presentation. Use "ExecuteScalar" which should work when you return a single value.
AcctNumber = ""
AcctNumber = cmd.ExecuteScalar
If AcctNumber = "" Then
Value = False
Else
Value = True
End If
Just to be sure it's not a data problem, parameterize your SQL. Change the statement:
Dim sql As String = "SELECT a.TelNumber, c.AccountNumber " & _
"FROM TelInfo a " & _
"INNER JOIN Customers b ON a.CustID = b.pkguidId " & _
"INNER JOIN Accounts c ON b.pkguidId = c.CustID " & _
"WHERE a.TelNumber = #telNumber"
Then do this:
Dim cmd As New SqlCommand(sql, conn)
cmd.Parameters.AddWithValue("#telNumber", NumberToCheck) ' <==== added line
Edit
I think we're looking in the wrong place. Add this just before if reader.Read():
Value = false
AcctNumber = ""
This will make sure you're not having a variable-scope problem. (You are using Option Strict On, right?)
In the immortal words of Homer Simpson... "DOH!!"
I just had a look on the database that my application searches for the telephone numbers and, I don't know how I could have missed it, but the value I'm searching for is actually there.
The problem is, therefore, not likely anything to do with my code, but rather the data...