Updating SQL database Issue [closed] - sql

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 4 years ago.
Improve this question
Thanks so much for your response. So I've made the changes you suggested, but i'm still not getting my database to update. The only thing that I have changed from your code is the MessageBox lines. I changed those to Alert messages. What am I missing here? Maybe my variables need to be declared differently Thanks!!!
Protected Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim x As Integer
Dim z As Integer
Dim r As Integer
Dim V1 As String
Dim V2 As String
x = txbPalletNumber.Text
z = txbOrderNumber.Text
r = txbShipmentNumber.Text
Try
Using conn As New OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\inetpub\wwwroot\Traceability\Traceability.accdb")
If Not Integer.TryParse(txbPalletNumber.Text, x) Then
Response.Write("<script type=""text/javascript"">alert(""Pallet Number must be a Number"");</script")
Exit Sub
End If
If Not Integer.TryParse(txbOrderNumber.Text, z) Then
Response.Write("<script type=""text/javascript"">alert(""Order Number must be a Number"");</script")
Exit Sub
End If
If Not Integer.TryParse(txbShipmentNumber.Text, r) Then
Response.Write("<script type=""text/javascript"">alert(""Shipment Number must be a Number"");</script")
Exit Sub
End If
Using cmd As New OleDbCommand("SELECT Status FROM tblPalletRecords WHERE Palletnumber = #x ", conn)
cmd.Parameters.Add("#x", OleDbType.Integer).Value = x
conn.Open()
V1 = CStr(cmd.ExecuteScalar())
conn.Close()
End Using
If V1 = "In Stock" Then
Using cmd2 As New OleDbCommand("UPDATE tblPalletRecords SET OrderNumber = #z, ShipmentNumber = #r WHERE PalletNumber = #x", conn)
cmd2.CommandText = "UPDATE tblPalletRecords SET OrderNumber = #z, ShipmentNumber = #r WHERE PalletNumber = #x "
cmd2.Parameters.Add("#z", OleDbType.Integer).Value = z
cmd2.Parameters.Add("#r", OleDbType.Integer).Value = r
cmd2.Parameters.Add("#x", OleDbType.Integer).Value = x
conn.Open()
cmd2.ExecuteNonQuery()
conn.Close()
End Using
Using cmd3 As New OleDbCommand("SELECT Status FROM tblPalletRecords WHERE Palletnumber = #x", conn)
cmd3.Parameters.Add("#x", OleDbType.Integer).Value = x
conn.Open()
V2 = CStr(cmd3.ExecuteScalar())
conn.Close()
End Using
Response.Write("<script type=""text/javascript"">alert(""The Status to " & x & " has Changed to " & V2 & """);</script")
Else
Response.Write("<script type=""text/javascript"">alert(""The Pallet is not In Stock to Ship"");</script")
End If
End Using
Catch ex As Exception
'Error handling
End Try
txbSearch.Text = txbPalletNumber.Text
GridView1.DataBind()
End Sub
End Class

You overwrite the value of your commandtext with a select statement before executing the update statement, so it is never run.

You can declare new oledbcommand since the last command overwrite the update command:
Dim cmd2 as New OleDbCommand
'Set the command properties.
cmd.Connection = conn
cmd.CommandText = "SELECT Status FROM tblPalletRecords WHERE Palletnumber = " & x & " "
V1 = cmd.ExecuteScalar()
If V1 = "In Stock" Then
cmd2.CommandText = "UPDATE tblPalletRecords SET OrderNumber = " & z & ", ShipmentNumber = " & r & " WHERE PalletNumber = " & x & " "
cmd.CommandText = "SELECT Status FROM tblPalletRecords WHERE Palletnumber = " & x & " "
V2 = cmd.ExecuteScalar()
Response.Write("<script type=""text/javascript"">alert(""The Status to " & x & " has Changed to " & V2 & """);</script")
Else
Response.Write("<script type=""text/javascript"">alert(""The Pallet is not In Stock to Ship"");</script")
End If
cmd2.ExecuteNonQuery()
conn.Close()

Turn on Option Strict now and for all your projects. Open your connection directly before your execute and close it immediately after. Check with TryParse that you have the correct numeric input. Use Parameters always. It will curtail the disastrous SQL injection and make your SQL statements easier to write. I have added Using..End Using statements. This will take care of Disposing your objects. It will also close your connection if an error occurs before a .Close() method is reached. I would have liked to reuse the x parameter but Access does not care about parameter names, only the order in the SQL statement so I used a new command each time. I have showed how to use Constructors to save a few lines of code; passing the connection string in the connection constructor and passing the CommandText and the Connection directly to the Command construtor. It appeared from your SQL statements, that x, z, and r are all numeric types not strings so I guessed at Integer. You may have to change this, depending on the datatype in the table.
Dim x As Integer
Dim z As Integer
Dim r As Integer
Dim V1 As String
Dim V2 As String
Try
Using conn As New OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\inetpub\wwwroot\Traceability\Traceability.accdb")
If Not Integer.TryParse(txbPalletNumber.Text, x) Then
MessageBox.Show("Please enter a number for the Pallet.")
Exit Sub
End If
If Not Integer.TryParse(txbOrderNumber.Text, z) Then
MessageBox.Show("Please enter a number for the Order Number.")
Exit Sub
End If
If Not Integer.TryParse(txbShipmentNumber.Text, r) Then
MessageBox.Show("Please enter a number for the Shipment Number.")
Exit Sub
End If
Using cmd As New OleDbCommand("SELECT Status FROM tblPalletRecords WHERE Palletnumber = #x ", conn)
cmd.Parameters.Add("#x", OleDbType.Integer).Value = x
conn.Open()
V1 = CStr(cmd.ExecuteScalar())
conn.Close()
End Using
If V1 = "In Stock" Then
Using cmd2 As New OleDbCommand("UPDATE tblPalletRecords SET OrderNumber = #z, ShipmentNumber = #r WHERE PalletNumber = #x", conn)
cmd2.CommandText = "UPDATE tblPalletRecords SET OrderNumber = #z, ShipmentNumber = #r WHERE PalletNumber = #x "
cmd2.Parameters.Add("#z", OleDbType.Integer).Value = z
cmd2.Parameters.Add("#r", OleDbType.Integer).Value = r
cmd2.Parameters.Add("#x", OleDbType.Integer).Value = x
conn.Open()
cmd2.ExecuteNonQuery()
conn.Close()
End Using
Using cmd3 As New OleDbCommand("SELECT Status FROM tblPalletRecords WHERE Palletnumber = #x", conn)
cmd3.Parameters.Add("#x", OleDbType.Integer).Value = x
conn.Open()
V2 = CStr(cmd3.ExecuteScalar())
conn.Close()
End Using
Response.Write("<script type=""text/javascript"">alert(""The Status to " & x & " has Changed to " & V2 & """);</script")
Else
Response.Write("<script type=""text/javascript"">alert(""The Pallet is not In Stock to Ship"");</script")
End If
End Using
Catch ex As Exception
'Error handling
End Try

You need to learn coding standard first, declaring variables like x,y,z, I haven't seen from quite long time.
You are overwriting cmd.CommandText
cmd.CommandText = "UPDATE tblPalletRecords SET OrderNumber = " & z & ", ShipmentNumber = " & r & " WHERE PalletNumber = " & x & " "
cmd.CommandText = "SELECT Status FROM tblPalletRecords WHERE Palletnumber = " & x & " "
V2 = cmd.ExecuteScalar()
To Fix:
cmd.CommandText = "UPDATE tblPalletRecords SET OrderNumber = " & z & ", ShipmentNumber = " & r & " WHERE PalletNumber = " & x & " "
cmd.ExecuteNonQuery()

Related

VB.Net ignores isDBNull condition

I'm programming a dog adoption form. It retrieves data from a Access DB then the user can adopt up to three dogs, each one of them specified in 3 different fields. I'm doing it this way because I previously tried to do it with arrays, with no luck.
The issue comes here (highlighted in bold):
Try
Dim conexion As New OleDb.OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=|DataDirectory|\PerrosDB.mdb;")
conexion.Open()
Dim cmd As New OleDb.OleDbCommand
cmd.Connection = conexion
cmd.CommandType = CommandType.Text
cmd.CommandText = "select adopcion1, adopcion2, adopcion3 from usuarios where codigo_usuario = " & FormPrincipal.codigo_usuario & ""
Dim dr As OleDb.OleDbDataReader
dr = cmd.ExecuteReader
While dr.Read()
**If dr.IsDBNull(1) Then
posicionAdopcion = 1
ElseIf dr.IsDBNull(2) Then
posicionAdopcion = 2
ElseIf dr.IsDBNull(3) Then
posicionAdopcion = 3
Else
MsgBox("Lo sentimos, solo puedes hacer un máximo de 3 adopciones")
Exit Sub**
End If
End While
dr.Close()
conexion.Close()
Catch ex As Exception
MsgBox(ex.Message & "Saliendo de la aplicación.")
Me.Close()
End Try
and
Try
Dim conexion As New OleDb.OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=|DataDirectory|\PerrosDB.mdb;")
conexion.Open()
Dim cmd As New OleDb.OleDbCommand
cmd.Connection = conexion
cmd.CommandType = CommandType.Text
**If (posicionAdopcion = 1) Then
cmd.CommandText = "UPDATE USUARIOS SET ADOPCION1 = '" & nombrePerro & "' WHERE codigo_usuario = " & FormPrincipal.codigo_usuario & ""
ElseIf (posicionAdopcion = 2) Then
cmd.CommandText = "UPDATE USUARIOS SET ADOPCION2 = '" & nombrePerro & "' WHERE codigo_usuario = " & FormPrincipal.codigo_usuario & ""
ElseIf (posicionAdopcion = 3) Then
cmd.CommandText = "UPDATE USUARIOS SET ADOPCION3 = '" & nombrePerro & "' WHERE codigo_usuario = " & FormPrincipal.codigo_usuario & ""
End If**
cmd.ExecuteNonQuery()
conexion.Close()
Catch ex As Exception
MsgBox(ex.Message & "Saliendo de la aplicación...")
Me.Close()
End Try
What I'm trying to do is to check if the adoption fields (adopcion1, adopcion2, adopcion3) are empty, if they are, place the name of the dog there. If they are not, check for the next free slot. If none available, print the corresponding error message. But what the program does is to overwrite the adopcion1 (first field) no matter what.
I have checked this thread, I may be having a similar issue misunderstanding isDBNull usage, but so far I'm trying to do what it's stated there with no result.
What I'm doing wrong?
I got it, as I expected it was a silly mistake: I was retrieving the first data field from 1, and not from 0. Thus skipping it entirely:
If dr.isDBNull(0) Then
posicionAdopcion = 1
But yes, the code seems clunky, didn't know about SQL parameters, going to check them ASAP.
Thanks for the help!

Cannot open any more tables - OleDbException was unhandled

Good Day,
My question is how to handle the exception or get rid of the error pertaining to "Cannot open any more tables". For an overview to the program I was creating, I pull out the record of subject in ms access 2007, I loop to that record to randomly assign a schedule and one by one I insert the newly record with assigned schedule in the table.
My program flow of inserting the record work only for a certain number of times, like almost 200 and at some point it stop and pop-up the oledbexception
Thanks in advance for your time on answering my question.
here is my code for more detailed overview of my program,
Private Sub Assignsched(ByVal rType As String, ByVal subjectCode As String, ByVal SecID As String, ByVal CourseCode As String)
If shrdcon.con.State = ConnectionState.Closed Then
shrdcon.con.Open()
End If
Dim RoomNum As Integer
dtARoom.Clear()
Dim stoploop As Boolean
Dim count As Integer = 0
Dim rm1 As String
RoomAssign = ""
rm1 = "SELECT * FROM tblRoom WHERE RoomType = '" & rType & "'"
Dim dat As New OleDbDataAdapter(rm1, shrdcon.con)
dat.Fill(ds, "ARoom")
stoploop = False
count = 0
Do Until stoploop = "True"
RoomNum = rndm.Next(0, ds.Tables("ARoom").Rows.Count)
RoomAssign = ds.Tables("ARoom").Rows(RoomNum).Item(1)
ScheduleGeneration()
If checkExisting(sTime, eTime, RoomAssign, daypick) = False Then
RoomA = RoomAssign
GenerateOfferingID()
Dim cmd1 As New OleDbCommand()
cmd1.CommandText = "INSERT INTO [tblSubjectOffer]([SubjectOID],[SubjectCode],[SectionID],[Day],[sTime],[eTime],[RoomName],[CourseCode]) VALUES('" & _
myId & "','" & subjectCode & "','" & SecID & "','" & daypick & "'," & sTime & "," & eTime & ",'" & RoomA & "','" & CourseCode & "')"
cmd1.Connection = shrdcon.con
cmd1.ExecuteNonQuery()
cmd1.Dispose()
Dim pipz As New OleDbCommand("Update tblGenerator Set NextNo='" & myId & "' where TableName ='" & "tblSubjectOffer" & "'", shrdcon.con)
pipz.ExecuteNonQuery()
pipz.Dispose()
stoploop = True
Else
stoploop = False
End If
If stoploop = False Then
If count = 30 Then
stoploop = True
Else
count = count + 1
End If
End If
Loop
End Sub
This is typical error happens with Microsoft Jet engine when You have exceeded the maximum number of open TableIDs allowed by the Microsoft Jet database engine, which is 2048 with Jet3.5 engine and 1024 with older engines.
Even though you are closing the Command objects after each use, you are still using the same connection for the whole process, which actually holds the TableID's and is at some point of time exceeding the number of allowed open TableID's.
A probable solution would be to update the Jet Engine with the latest, which is available here
It might solve your problem, but if you are already using the latest engine, you have to look into other options to reduce the number of DB operations.
Try using the UpdateBatch method for applying the updates as a batch.
Hope this helps
Private Sub Command1_Click()
Dim myConnection As ADODB.Connection
Dim rsData As ADODB.Recordset
Set myConnection = New ADODB.Connection
myConnection.ConnectionString = "xxxxxxxxxxxxxxxxxxxx"
myConnection.Open
Set rsData = New ADODB.Recordset
rsData.CursorLocation = adUseClient
rsData.Open "select * from mytable", myConnection, adOpenStatic, adLockBatchOptimistic
For i = 1 To 10000
rsData.AddNew
rsData.Fields(0).Value = 1
rsData.Fields(1).Value = 2
Next i
rsData.UpdateBatch
rsData.Close
myConnection.Close
Set rsData = Nothing
End Sub
Good Evening,
Recently I encounter this type of error and i was able to resolve it by adding
con.close and call conState (a procedure conState- check below) before any insert/update or select statement
In my code i have something like
For i = 0 To DataGridView1.RowCount - 1
reg = DataGridView1.Rows(i).Cells(0).Value
Label2.Text = reg
'i added this two lines
***con.Close()***
***Call conState()***
Dim cmdcheck As New OleDbCommand("Select * from [2015/2016 UG CRF] where regno ='" & reg & "'", con)
Dim drcheck As OleDbDataReader
drcheck = cmdcheck.ExecuteReader
If drcheck.Read = True Then
GoTo A
End If
coursesFirst = String.Empty
coursesSecond = String.Empty
creditFirst = 0
creditSecond = 0
Dim cmdlevel As New OleDbCommand("Select * from [2015/2016 UG registration Biodata 5 april 16] where regno ='" & reg & "'", con)
Dim drlevel As OleDbDataReader
drlevel = cmdlevel.ExecuteReader
If drlevel.Read = True Then
level = drlevel.Item("level").ToString
faculty = drlevel.Item("faculty").ToString
program = drlevel.Item("programme").ToString
End If
...............
next
The conState is a connection testing if connection is closed is should open it again like in below
Public Sub conState()
If con.State = ConnectionState.Closed Then
con.Open()
End If
End Sub
This stop the error message
I got this exception in my C# application and the cause was using OleDbDataReader instances without closing them:
OleDbDataReader reader = cmd.ExecuteReader();
bool result = reader.Read();
reader.Close(); // <= Problem went away after adding this
return result;

if record exists update else insert sql vb.net

I have the following problem, I am developing a Clinic application using vb.net, the doctor has the ability to add medical information using checkboxes checkbox2.text = "Allergy" textbox15.text is the notes for Allergy, I want to insert the record if the patient's FileNo(Textbox2.text) doesn't exist, if it does then update the notes only, so far I was able to update it after 3 button clicks I don't know why????
any help is appreciated :)
thanks in advance
Dim connection3 As New SqlClient.SqlConnection
Dim command3 As New SqlClient.SqlCommand
Dim adaptor3 As New SqlClient.SqlDataAdapter
Dim dataset3 As New DataSet
connection3.ConnectionString = ("Data Source=(LocalDB)\v11.0;AttachDbFilename=" + My.Settings.strTextbox + ";Integrated Security=True;Connect Timeout=30")
command3.CommandText = "SELECT ID,Type FROM Medical WHERE FileNo='" & TextBox2.Text & "';"
connection3.Open()
command3.Connection = connection3
adaptor3.SelectCommand = command3
adaptor3.Fill(dataset3, "0")
Dim count9 As Integer = dataset3.Tables(0).Rows.Count - 1
If count9 > 0 Then
For countz = 0 To count9
Dim A2 As String = dataset3.Tables("0").Rows(countz).Item("Type").ToString
Dim B2 As Integer = dataset3.Tables("0").Rows(countz).Item("ID")
TextBox3.Text = A2
If A2 = CheckBox1.Text Then
Dim sql4 As String = "update Medical set MNotes=N'" & TextBox22.Text & "' where FileNo='" & TextBox2.Text & "' and Type = '" & CheckBox1.Text & "' and ID='" & B2 & "';"
Dim cmd4 As New SqlCommand(sql4, connection3)
Try
cmd4.ExecuteNonQuery()
Catch ex As Exception
MsgBox(ex.Message)
End Try
ElseIf A2 = CheckBox2.Text Then
Dim sql4 As String = "update Medical set MNotes=N'" & TextBox15.Text & "' where FileNo='" & TextBox2.Text & "' and Type = '" & CheckBox2.Text & "' and ID='" & B2 & "';"
Dim cmd4 As New SqlCommand(sql4, connection3)
Try
cmd4.ExecuteNonQuery()
Catch ex As Exception
MsgBox(ex.Message)
End Try
End If
Next
Else
If CheckBox1.Checked = True Then
Dim sql4 As String = "insert into Medical values('" & CheckBox1.Text & "',N'" & TextBox22.Text & "','" & TextBox2.Text & "')"
Dim cmd4 As New SqlCommand(sql4, connection3)
Try
cmd4.ExecuteNonQuery()
Catch ex As Exception
MsgBox(ex.Message)
End Try
End If
If CheckBox2.Checked = True Then
Dim sql4 As String = "insert into Medical values('" & CheckBox2.Text & "',N'" & TextBox15.Text & "','" & TextBox2.Text & "')"
Dim cmd4 As New SqlCommand(sql4, connection3)
Try
cmd4.ExecuteNonQuery()
Catch ex As Exception
MsgBox(ex.Message)
End Try
End If
End If
I think one of your problems may be related to your reducing the count of your table rows by 1 and then testing it above 0:
Dim count9 As Integer = dataset3.Tables(0).Rows.Count - 1
If count9 > 0 Then
Try changing to:
Dim count9 As Integer = dataset3.Tables(0).Rows.Count
If count9 > 0 Then
Also, make sure one of the check-boxes (CheckBox1 or CheckBox2) mentioned later in your code is ticked.
-- EDIT --
Sorry - didn't explain why! The reason is that the majority of array/list like structures in .NET are zero based (i.e. start counting from 0 instead of 1).
The best course of action for you is to maximize your productivity by allowing SQL to do what it does best. Assuming you are using SQL Server 2008, the MERGE function is an excellent use case for the conditions that you have supplied.
Here is a very basic example that is contrived based upon some of your code:
CREATE PROCEDURE [dbo].[csp_Medical_Merge]
#MType int, #FileNo varchar(20), #MNotes varchar(max), #ID int, #OtherParams
AS
BEGIN
MERGE INTO [DatabaseName].dbo.Medical AS DEST
USING
(
/*
Only deal with data that has changed. If nothing has changed,
then move on.
*/
SELECt #MType, #MNotes, #FileNo, #ID, #OtherParams
EXCEPT
Select [Type], MNotes, FileNo, ID, OtherFields from [DatabaseName].dbo.Medical
) As SRC ON SRC.ID = DEST.ID
WHEN MATCHED THEN
UPDATE SET
DEST.MNOTES = SRC.MNOTES,
DEST.FileNo = SRC.FileNo,
DEST.Type = SRC.Type
WHEN NOT MATCHED BY TARGET THEN
INSERT (FieldsList)
VALUEs (FileNo, MNotes, etc, etc);
END
GO

ODBC - unable to allocate an environment handle

Hi I am trying to insert data into Navision database from a DataTable. That DataTable contain around 5000 records, if the records count is less then it's working fine but record count is around 5000 I am getting this error.
ERROR - unable to allocate an environment handle.
This is the code I am using
Public Function InsertToHHTTransferLine(ByVal dtTransferLn As DataTable, ByVal hhtNumber As String) As Integer
Dim result As Integer
Dim cn As OdbcConnection
Dim dtTransferLine As DataTable
cn = New OdbcConnection(ConnStr)
Dim SqlStr As String = ""
Try
cn.Open()
dtTransferLine = dtTransferLn
Dim DocType As String
DocType = "Purchase"
Dim cmd As OdbcCommand
Dim hhtNo As String
hhtNo = hhtNumber
If dtTransferLine.Rows.Count > 0 Then
For i As Integer = 0 To dtTransferLine.Rows.Count - 1
If dtTransferLine.Rows(i)("DOC_TYPE").ToString() = "0" Then
DocType = "Purchase"
End If
If dtTransferLine.Rows(i)("DOC_TYPE").ToString() = "1" Then
DocType = "Transfer Receipt"
End If
If dtTransferLine.Rows(i)("DOC_TYPE").ToString() = "2" Then
DocType = "Transfer Shipment"
End If
If dtTransferLine.Rows(i)("DOC_TYPE").ToString() = "3" Then
DocType = "Stock Count"
End If
Try
SqlStr = "INSERT INTO ""HHT & Navision Line""(""Document Type"",""Document No_"",""HHT No_"",""Line No_"",""Item No_"",""Document Quantity"",""Scan Quantity"",""Unit Price"",""Posted"") VALUES('" & DocType & "','" & dtTransferLine.Rows(i)("DOC_NO").ToString() & "','" & hhtNo & "','" & dtTransferLine.Rows(i)("LINE_NO").ToString() & "','" & dtTransferLine.Rows(i)("ITEM_NO").ToString() & "'," & dtTransferLine.Rows(i)("DOC_QTY").ToString() & "," & dtTransferLine.Rows(i)("SCAN_QTY").ToString() & "," & dtTransferLine.Rows(i)("UNIT_PRICE").ToString() & ",0)"
cmd = New OdbcCommand(SqlStr, cn)
result = cmd.ExecuteNonQuery()
Catch ex As Exception
If (ex.Message.IndexOf("Illegal duplicate key") <> -1) Then
CreateLog(SqlStr, "User1", "Duplicate()", ex.Message)
Else
CreateLog(SqlStr, "User1", "Other()", ex.Message)
End If
'CreateLog(SqlStr, "User1", "Other()", ex.Message)
End Try
Next
End If
Catch ex As Exception
CreateLog(SqlStr, "User1", "InsertToHHTTransferLine()", ex.Message)
result = -1
Finally
cn.Close()
cn.Dispose()
End Try
Return result
End Function
Could be that "cmd" variables need to be disposed before creating new ones?
At least this is the only thing I can see in the code where you are consuming resources in a loop depending on the number of records.
Anyway this should be easy to identify with a debugger, just figure out the line giving you the error, and that will lead you to the answer.

Vb.net with access database: How can you help me simplify these codes?

this is my code:
'Set up connection string
Dim cnString As String
cnString = "Provider=Microsoft.Jet.OLEDB.4.0;Persist Security Info=False;Data Source=..\data\testingDB.mdb"
Dim sqlQRY As String = "SELECT * " & _
"FROM users " & _
"WHERE firstName = '" & TextBox1.Text & "' " & _
" AND lastName = '" & TextBox2.Text & "'"
'Create connection
Dim conn As OleDbConnection = New OleDbConnection(cnString)
Try
' Open connection
conn.Open()
'create data adapter
Dim da As OleDbDataAdapter = New OleDbDataAdapter(sqlQRY, conn)
'create dataset
Dim ds As DataSet = New DataSet
'fill dataset
da.Fill(ds, "user")
'get data table
Dim dt As DataTable = ds.Tables("user")
'display data
Dim row As DataRow
If TextBox1.Text = dt.Rows(0).Item(1) And TextBox2.Text = dt.Rows(0).Item(2) And dt.Rows(0).Item(5) = 10 Then
MsgBox("10")
ElseIf TextBox1.Text = dt.Rows(0).Item(1) And TextBox2.Text = dt.Rows(0).Item(2) And dt.Rows(0).Item(5) = 9 Then
MsgBox("9")
ElseIf TextBox1.Text = dt.Rows(0).Item(1) And TextBox2.Text = dt.Rows(0).Item(2) Then
MsgBox("SUCCESS")
Else
MsgBox("fail")
End If
Catch ex As OleDbException
MsgBox("Error: " & ex.ToString & vbCrLf)
Finally
' Close connection
conn.Close()
End Try
I'm trying it to make it simple with the same results. As you can see the if-else statements were messy but it works 100%. I do want the if-else statements to be simple and works the same as above.
Edited to check value of row(5) for DbNull values
try this for if-else statements:
Dim row As DataRow = dt.Rows(0)
Dim r5 as Object = row(5)
If IsDbNull(r5) then r5 = 0
If TextBox1.Text = row(1) And TextBox2.Text = row(2) Then
Select Case r5
Case 10, 9 : MsgBox(r5)
Case Else : MsgBox("SUCCESS")
End Select
Else
MsgBox("fail")
End If
Dim cmd as New OledbCommand
Dim sqlQRY As String = "SELECT count(*) " & _
"FROM users " & _
"WHERE firstName = #fname " & _
" AND lastName = #lname"
cmd.parameters.add("#fname",TextBox1.Text)
cmd.parameters.add("#lname",TextBox2.Text)
Dim Cnt as Integer
cmd = new oledbcommand(sqlQRy,con)
Cnt = Convert.ToInt32( cmd.ExecuteScalar())
if Cnt>=1 then
msgbox("Success")
else if
msgbox("Failure")
end if
You must be aware that your SQL could logically return more than 1 row. You need to make sure that when you read data that you intend to test in this way, that your SQL uses a primary key and return 1 row only otherwise, problems could happen when more data is added. I suggest you first ensure that exactly 1 row is returned before you perform your if test (see my comment to #SenthilKumar). You need to send appropriate message to user when no rows are found and not perform the test.
If you get exactly 1 row back, you have to ensure that the data is not null (if applicable, this depends on how your columns are defined).
Remember that data that comes form UI could be padded with blanks or be in mixed case. You may need to watch for this.
Your IF statement is not too complex as is.I am not sure what you are testing exactly, but one can observe that you are using the following conditions:
TextBox1.Text = dt.Rows(0).Item(1) And TextBox2.Text = dt.Rows(0).Item(2) And dt.Rows(0).Item(5)
TextBox1.Text = dt.Rows(0).Item(1) And TextBox2.Text = dt.Rows(0).Item(2) And dt.Rows(0).Item(5)
TextBox1.Text = dt.Rows(0).Item(1) And TextBox2.Text = dt.Rows(0).Item(2)
You can see that the the expression
dt.Rows(0).Item(1) And TextBox2.Text = dt.Rows(0).Item(2) is common. You can assign the value to a Boolean expression and use it in your test.
You also should not include non-database processing in the scope of your try.
Just more little simpler ..
If TextBox1.Text = dt.Rows(0).Item(1) And TextBox2.Text = dt.Rows(0).Item(2)
MsgBox("SUCCESS - " & format(dt.Rows(0).Item(5)))
Else
MsgBox("fail")
End If