if record exists update else insert sql vb.net - sql

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

Related

Updating SQL database Issue [closed]

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()

How to know the available time and date in Reservation/CheckIn Program

I am using Visual Basic.Net and I have a problem in knowing the available Date, Time, and Room for the reservation/checkin of Hotel/Resort Reservation Program. Here in this code provided below, when I tried to reserve the specific room in a specific date and time, then restart the program, when I tried to save again with the unavailable room/date/time, the program's condition has wrongly allowed to save it again with the conflict schedule. I am using visual basic. Thank you :)
Dim varConflictSched As Boolean = False
Dim dsCheckIn As New DataSet
Dim daCheckIn As OdbcDataAdapter = New OdbcDataAdapter("SELECT * FROM tblCheckIn ORDER BY ID", MyConn)
daCheckIn.Fill(dsCheckIn, "tblCheckIn")
Dim DateTimeRangeNewIn(Val(Me.txtstaying.Text)) As DateTime
Dim DateCheckInNew As DateTime = Me.dtpCheckIn.Value
For a As Integer = 0 To dsCheckIn.Tables("tblCheckIn").Rows.Count - 1
Dim DateTimeRangeOldIn(dsCheckIn.Tables("tblCheckIn").Rows(a)("Staying")) As DateTime
REM Check if the room number is in used
If Me.cbRoomNumber.SelectedItem = dsCheckIn.Tables("tblCheckIn").Rows(a)("RoomNumber").ToString Then
REM Check if the date and time of the specified room number is in used
Dim varCheckInDate As DateTime = dsCheckIn.Tables("tblCheckIn").Rows(a)("CheckInDate")
For b As Integer = 0 To dsCheckIn.Tables("tblCheckIn").Rows(a)("Staying")
For c As Integer = 0 To Val(Me.txtstaying.Text)
DateTimeRangeOldIn(b) = varCheckInDate.AddDays(b)
DateTimeRangeNewIn(c) = DateCheckInNew.AddDays(c)
If DateTimeRangeOldIn(b).Date = DateTimeRangeNewIn(c).Date Then
If DateDiff(DateInterval.Minute, DateTimeRangeOldIn(b), DateTimeRangeNewIn(c)) <= 0 Then
varConflictSched = True
Exit For
End If
End If
Next
Next
End If
Next
If Me.txtAmount.Text = "" Or Me.txtSearch.Text = "" Or Me.txtstaying.Text = "" Or Me.txtTotal.Text = "" Or Me.cbRoomNumber.SelectedIndex = -1 Or Me.cbRoomtype.SelectedIndex = -1 Then
MessageBox.Show("Required field(s) should not be left blank" & vbCrLf & "Please try again", "NO BLANK SPACE", MessageBoxButtons.OK, MessageBoxIcon.Error)
ElseIf varConflictSched = True Then
MessageBox.Show("Can't set schedule with this date." & vbCrLf & "Please insert another date.", "CONFLICT", MessageBoxButtons.OK, MessageBoxIcon.Error)
Else
Dim DAdapter As OdbcDataAdapter = New OdbcDataAdapter("SELECT * FROM tblCheckIN ORDER BY ID ", MyConn)
Dim DSet As New DataSet
DAdapter.Fill(DSet, "tblCheckIN")
Dim NewID As Integer = DSet.Tables("tblCheckIN").Rows(DSet.Tables("tblCheckIN").Rows.Count - 1)("ID") + 1
Dim CommCheckIn As OdbcCommand = New OdbcCommand("INSERT INTO tblCheckIN (ID,CustomerID,Roomtype,RoomNumber,Amount,CheckInDate,Staying)VALUES(" & NewID & ",'" & Me.txtSearch.Text & "','" & Me.cbRoomtype.SelectedItem & "','" & Me.cbRoomNumber.SelectedItem & "','" & Me.txtAmount.Text & "','" & Me.dtpCheckIn.Value & "' , '" & Me.txtstaying.Text & "')", MyConn)
MyConn.Open()
CommCheckIn.ExecuteNonQuery()
MyConn.Close()
MessageBox.Show("Your Checking-In is succesfully saved. ", "SAVED", MessageBoxButtons.OK, MessageBoxIcon.Information)
Me.ClearAll()
End If
You don’t need looping code to find a collision.
A collision occurs when:
RequestionStartDate <= EndDate
And
RequestEndDate >= StartDate
Of course you have to add roomnumber to above, but it rather simple.
So on book button, your code will do this:
Dim strSQL As String
Dim rstData As New DataSet
Dim daRead As SqlDataAdapter
strSQL = "select * from tblCheckIn where RoomNumber = #RoomNum " & _
" AND ( (#CheckIn <= CheckOutDate) AND (#CheckOut >= CheckInDate) )"
Dim MySql As SqlCommand = New SqlCommand(strSQL, GetCon)
MySql.Parameters.Add("#RoomNum", SqlDbType.Int).Value = Me.RoomNumber.Value
MySql.Parameters.Add("#CheckIn", SqlDbType.DateTime).Value = Me.dtpCheckIn.Value
MySql.Parameters.Add("#CheckOut", SqlDbType.DateTime).Value = Me.dtpCheckOut.Value
daRead.SelectCommand = MySql
daRead.Fill(rstData)
If rstData.Tables(0).Rows.Count > 0 Then
MsgBox("you have a booking collsion")
End If
The above works since you never allow a collsion, and the above will return any record that you "over lap". this includes the cases like this:
RequestStart RequestEnd
| |
| exsiting Start/end |
or
RequestStart RequestEnd
| |
| exist Start Exist end |
or
RequestStart RequestEnd
| |
| exist Start Exist end |
in fact any combination of ANY overlap will be found by the above simple query.

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;

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