VB.NET updating .accdb records - vb.net

I'm working on a VB.Net application that interfaces with an .accdb file to create and (eventually) update records on two tables in the same database. I'm able to write new information to a table no problem, however it is updating/changing/adding additional information to that same row in the table I'm having issues with. My code for writing updates to an existing row is at the bottom of my post.
The biggest issue I'm having is, after I execute this subroutine, it fails at the objCmd.ExecuteNonQuery() with the error message IErrorInfo.GetDescription failed with E_FAIL(0x80004005). I've combed through here and Google, trying different methods and moving things around and I cannot figure out what I'm missing. As far as I can tell, I am not using any reserved words in my SQL query. The block under the Else statement does work for creating new rows (I don't have issues with that side of my program), maybe the syntax is different for doing UPDATE commands? Any help/insight is greatly appreciated.
Private Sub WriteToDatabase()
strcs = txtSerialNumber.Text
strOrderType = orderType
strPoRMA = txtPoRMA.Text
strtech = cboTech.Text
strDate = calendarTest.SelectionStart
'Write to database if Production
If strOrderType = "PO" Then
'Check database for duplicate record
strSQL = "SELECT * FROM [New Camera Database] WHERE cameraSer=" & strcs
objCmd = New OleDbCommand(strSQL, dbconn)
dr = objCmd.ExecuteReader
dr.Read()
If dr("calCompleteDate").ToString <> "" Then
MsgBox("Camera S/N " & strcs & " completed " & dr("calCompleteDate") & ". Use Lookup to reprint Cert. of Compliance", vbOK + vbExclamation,
"Camera S/N " & strcs & " already completed")
exitFlag = True
Else
'Write to New Camera Database Table
strSQL = "UPDATE [New Camera Database] SET poNum=#poNum , calCompleteDate=#calCompleteDate, calCompleteTech=#calCompleteTech WHERE cameraSer=" & strcs
objCmd = New OleDbCommand(strSQL, dbconn)
objCmd.Parameters.AddWithValue("#poNum", strPoRMA)
objCmd.Parameters.AddWithValue("#calCompleteDate", strcs)
objCmd.Parameters.AddWithValue("#calCompleteTech", strtech)
objCmd.ExecuteNonQuery()
'Write to up2DateTravelers Table
strSQL = "UPDATE up2DateTravelers SET poRMANum = #poRMANum, calCompleteDate = #calCompleteDate, calCompleteTech = #calCompleteTech WHERE cameraSer=" & strcs
objCmd = New OleDbCommand(strSQL, dbconn)
objCmd.Parameters.AddWithValue("#poRMANum", strPoRMA)
objCmd.Parameters.AddWithValue("#calCompleteDate", strcs)
objCmd.Parameters.AddWithValue("#calCompleteTech", strtech)
objCmd.ExecuteNonQuery()
End If
ElseIf strOrderType = "RMA" Then
'Create new functions, userform, etc (TBD)
End If
btnClear.PerformClick()
End Sub

I guess this line :
objCmd.Parameters.AddWithValue("#calCompleteDate", strcs)
is a mistake and that you wanted to use the Date :
objCmd.Parameters.AddWithValue("#calCompleteDate", strDate)
Also, Use Using and parametrized queries :
'Write to New Camera Database Table
strSQL = "UPDATE [New Camera Database] SET poNum=#poNum , calCompleteDate=#calCompleteDate, calCompleteTech=#calCompleteTech WHERE cameraSer=#cameraSer"
Using objCmd As New OleDbCommand(strSQL, dbconn)
objCmd.Parameters.AddWithValue("#poNum", strPoRMA)
objCmd.Parameters.AddWithValue("#calCompleteDate", strDate)
objCmd.Parameters.AddWithValue("#calCompleteTech", strtech)
objCmd.Parameters.AddWithValue("#cameraSer", strcs)
objCmd.ExecuteNonQuery()
End Using
'Write to up2DateTravelers Table
strSQL = "UPDATE up2DateTravelers SET poRMANum = #poRMANum, calCompleteDate = #calCompleteDate, calCompleteTech = #calCompleteTech WHERE cameraSer=#cameraSer"
Using objCmd As New OleDbCommand(strSQL, dbconn)
objCmd.Parameters.AddWithValue("#poRMANum", strPoRMA)
objCmd.Parameters.AddWithValue("#calCompleteDate", strDate)
objCmd.Parameters.AddWithValue("#calCompleteTech", strtech)
objCmd.Parameters.AddWithValue("#cameraSer", strcs)
objCmd.ExecuteNonQuery()
End Using

Related

how to reduce quantity using vb.net

has an error (An unhandled exception of type 'System.ArgumentOutOfRangeException' occurred in mscorlib.dll
Additional information: Index and length must refer to a location within the string.)
mycmd.Connection = myconnection.open
Dim dami As Integer = quantityt.Text
mycmd.CommandText = "Update inventory set total_quantity=total_quantity-'" & dami & "' where item_code='" & itemcodet.Text & "'"
mycmd.ExecuteNonQuery()
MsgBox("stocks decrease!!", MsgBoxStyle.Information, "Noticed..")
myconnection.close()
I think you have problem with following line
mycmd.CommandText = "Update inventory set total_quantity=total_quantity-'" & dami & "' where item_code='" & itemcodet.Text & "'"
should be
mycmd.CommandText = "Update inventory set total_quantity=total_quantity-" & dami & " where item_code='" & itemcodet.Text & "'"
dont use apostrophe ' when counting with integer.. apostrophes use only in case of string
I used the SQL server provider for demonstration. Change to whatever database you are using. Check the actual data types of your fields in your database. Open the connection at the last minute. See my comment about Using blocks.
Private Sub OPCode()
Using myconnection As New SqlConnection("Your connection string")
Using mycmd As New SqlCommand("Update inventory set total_quantity = total_quantity - #dami where item_code = #itemCode;", myconnection)
mycmd.Parameters.Add("#dami", SqlDbType.Int).Value = CInt(quantityt.Text)
mycmd.Parameters.Add("#itemCode", SqlDbType.VarChar).Value = itemcodet.Text
myconnection.Open()
mycmd.ExecuteNonQuery()
End Using
End Using
MsgBox("stocks decrease!!", MsgBoxStyle.Information, "Noticed..")
End Sub

"Operation must be an updateable query" VB.Net OleDB for Excel

Ive been trying to find a solution for this problem without any success:
I'm using VB.NET and I need to read and update records from an Excel file. I use the OleDB API for that. It works fine for all the reading, but impossible to write to the file (Update or Insert queries)
Here is what I have:
My connection string:
Public connString As String = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\Users\...\Resources\attempt.xls;Extended Properties='Excel 8.0;HDR=YES;IMEX=1;'"
Select query that works fine:
Dim checkQuery = "SELECT * FROM [Sheet1$] WHERE [TravellerPN] = #T"
Try
Using connection As New OleDb.OleDbConnection(Form.connString)
Dim checkCommand As New OleDbCommand(checkQuery, connection)
checkCommand.Parameters.Add("#T", OleDbType.VarChar).Value = PN
connection.Open()
Dim reader As OleDbDataReader = checkCommand.ExecuteReader()
Dim path As String = ""
While reader.Read()
path = reader("Datapath").ToString
End While
reader.Close()
MsgBox(PN & " " & DP & " " & path,,)
If a record for the part number entered doesnt exist, and nothing is returned, insert a new line
If path = "" Then
Dim addQuery = "INSERT INTO [Sheet1$] ([TravellerPN],[Datapath]) VALUES (#T, #D)"
Dim addCommand As New OleDbCommand(addQuery, connection)
addCommand.Parameters.Add("#T", OleDbType.VarChar).Value = PN
addCommand.Parameters.Add("#D", OleDbType.VarChar).Value = DP
Dim rows As Integer = addCommand.ExecuteNonQuery()
And this was where it returns the error.
MsgBox(rows & " row added!",, "") 'Never diplayed
And other query that doesn't work either:
Else 'If does exist, confirm replacement'
Dim replaceResponse = MsgBox("A path already exists for " & PN & "." & vbNewLine & "Do you want to replace " & path & " with " & DP & "?", MsgBoxStyle.YesNo, "Overwrite previous datapath?")
Dim replaceQuery = "UPDATE [Sheet1$] SET [Datapath] = #D WHERE [TravellerPN]=#T"
Dim replaceCommand As New OleDbCommand(replaceQuery, connection)
replaceCommand.Parameters.Add("#D", OleDbType.VarChar).Value = DP
replaceCommand.Parameters.Add("#T", OleDbType.VarChar).Value = PN
Dim rows As Integer = replaceCommand.ExecuteNonQuery()
MsgBox(rows & " row updated!",, "")
End If
connection.Close()
End Using
I've tried to fix the issue: it could be caused by permissions, so I authorized even guests accounts to modify my folder.
If it were a ReadOnly mode in the connection: I tried adding Mode=ReadWrite but my connection String didn't work after that. (That option seems only available for ADO connections?)
I tried running the app as administrator
And finally, I'm posting this here hoping to get some help.
Sorry or the long post, I was trying to give all the elements that could potentially be a problem.
Thanks.

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!

how validate if record not found on database in 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

Import excel sheet to sql database VB Net client

I have some code I was hoping someone could look at for performance improvements. I have a spreadsheet that I need to import weekly. The sheet has 112 columns and about 35,000 rows. The code I have works, but it takes about 20 minutes to import the data. The excel column names do not match the database column names (I inherited this). Here is the code I am using. (I removed alot of the fields so it is easier to read)
'Connection String to Excel Workbook
Dim excelConnectionString As String = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" & MyFile & ";Extended Properties=""Excel 12.0;HDR=Yes;"""
' Create Connection to Excel Workbook
Using connection As New System.Data.OleDb.OleDbConnection(excelConnectionString)
'List columns you need from the Excel file
Dim command As New System.Data.OleDb.OleDbCommand("Select * FROM [" & txtSheetName.Text & "$]", connection)
connection.Open()
' Create DbDataReader to Data Worksheet
Using dr As System.Data.OleDb.OleDbDataReader = command.ExecuteReader()
Dim strSql As String = ""
strSql = "INSERT INTO MyTestTable (" & _
"State, [Store Code], [Store Name], [Store Zone Code], [Store Zone Code Name], " & _
"WeekProd, YTDNew, " & _
"UpdatedBy, DateUpdated" & _
") VALUES (" & _
"#State, #StoreCode, #StoreName, #StoreZoneCode, #StoreZoneCodeName, " & _
"#WeekProd, #YTDNew, " & _
"#UpdatedBy, #DateUpdated" & _
Try
If dr.HasRows() Then
While dr.Read()
If Convert.ToString(dr.Item(0)) <> "" Then
Dim MyZone As String = Convert.ToString(dr.Item(1))
MyZone = StrConv(MyZone, vbProperCase)
Dim cmd As New SqlClient.SqlCommand
cmd.Connection = cn
cmd.CommandType = CommandType.Text
cmd.CommandText = strSql
cmd.Parameters.Add("#State", SqlDbType.VarChar).Value = ""
cmd.Parameters.Add("#StoreCode", SqlDbType.VarChar).Value = Convert.ToString(dr.Item(0))
cmd.Parameters.Add("#StoreName", SqlDbType.VarChar).Value = MyZone
cmd.Parameters.Add("#StoreZoneCode", SqlDbType.VarChar).Value = Convert.ToString(dr.Item(2))
cmd.Parameters.Add("#StoreZoneCodeName", SqlDbType.VarChar).Value = Convert.ToString(dr.Item(3))
cmd.Parameters.Add("#WeekProd", SqlDbType.Float).Value = Convert.ToDecimal(dr.Item(93))
cmd.Parameters.Add("#YTDNew", SqlDbType.Float).Value = Convert.ToDecimal(dr.Item(94))
cmd.Parameters.Add("#UpdatedBy", SqlDbType.VarChar).Value = MyUser.Substring(MyUser.Length - 4)
cmd.Parameters.Add("#DateUpdated", SqlDbType.Date).Value = Date.Today()
cmd.ExecuteScalar()
End If
End While
End If
Catch ex As Exception
lblMessage.Text = ex.Message
Exit Sub
Finally
cn.Close()
cn = Nothing
End Try
End Using
End Using
Won't promise this will set the world on fire performance-wise, but it might help.
My first thought would be to not create a new SqlCommand object and parameter set for every row in the Excel table. I would create it one time (which should save you the overhead of about 35K object instantiations given your data size), establish the parameter names, all outside the reader loop, and then call SetParameter to set the values for each column as each row in the Excel is traversed. That should trade you the overhead of about 35K * (number of real fields) parameter addition calls for setparameter calls to existing parameters. And I would also change the call type to ExecuteNonQuery rather than ExecuteScalar.
Now, ordinarily, the conventional wisdom would hold that you only open/close a connection to a database as you need it, and I think that is implied in this structure (open/close for each insert) but in this case, for a data update scenario like this, I think this would be a reasonable exception.