SQL CommandText Throwing error [VB.NET] using msaccess database [closed] - sql

Closed. This question needs to be more focused. It is not currently accepting answers.
Closed 13 days ago.
Locked for 4 days. There are disputes about this question’s content being resolved at this time. It is not currently accepting new answers or interactions.
sqlconn.ConnectionString = MyCon
sqlquery.Connection = sqlconn
sqlconn.Open()
sqlquery.CommandText = "UPDATE " + MyTable + " SET [Name of the Insurance Company] = #INSURANCECOM, [Name of the Policy Holder] = #HOLDERNAME,
[Policy Number] = #POLNUMBER, [Name of the Plan] = #PLANNAME, [Table / Plan Number] = #PLANNUMBER, [Policy Term] = #POLTERM,
[Premium Payment Term] = #PREMIUMTERM, [Date of Commencement] = #COMMENCEMENT, [Sum Assured] = #ASSUREDSUM, [Maturity Date] = #MATDATE,
[Premium Amount] = #PREMAMT, [Frequency of Payment of Premium] = #FREQUENCY, [Date of Last Premium Payment] = #LASTPAYMENT WHERE ID = #PID"
MsgBox(sqlquery.CommandText.ToString + CURRCELL)
sqlquery.Parameters.AddWithValue("#INSURANCECOM", CStr(TxtInsName.Text.ToString))
sqlquery.Parameters.AddWithValue("#HOLDERNAME", Txtholder.Text.ToString)
sqlquery.Parameters.AddWithValue("#POLNUMBER", TxtPolNo.Text.ToString)
sqlquery.Parameters.AddWithValue("#PLANNAME", TxtPlan.Text.ToString)
sqlquery.Parameters.AddWithValue("#PLANNUMBER", TxtPlanNo.Text.ToString)
sqlquery.Parameters.AddWithValue("#POLTERM", TxtPolterm.Text.ToString)
sqlquery.Parameters.AddWithValue("#PREMIUMTERM", TxtPaymentTerm.Text)
sqlquery.Parameters.AddWithValue("#COMMENCEMENT", DateOfCommencement.Value.ToShortDateString)
sqlquery.Parameters.AddWithValue("#ASSUREDSUM", TxtSumAssured.Text)
sqlquery.Parameters.AddWithValue("#MATDATE", DateMaturity.Value.ToShortDateString)
sqlquery.Parameters.AddWithValue("#PREMAMT", PREMIUMAMOUNT.Text)
sqlquery.Parameters.AddWithValue("#FREQUENCY", TxtFrequency.Text.ToString)
sqlquery.Parameters.AddWithValue("#LASTPAYMENT", DateLast.Value.ToShortDateString)
sqlquery.Parameters.AddWithValue("#NOMINEE", TxtNominee.Text.ToString)
sqlquery.Parameters.AddWithValue("#OTHER", TxtOther.Text.ToString)
sqlquery.Parameters.AddWithValue("#PID", CURRCELL.ToString)
''#PID
sqlquery.ExecuteNonQuery()
sqlconn.Close()
MyTable = ""
MsgBox("Updated !!")
isupdate = False
Me.Close()
its not even hitting to the line
'msgbox("commandtext")'
while stepping through the code, after sqlquery.commandtext line directly jumping to the catch statement
getting following error
SaveError:
Conversion from string "UPDATE Insurance SET [Name of t" to type 'Double' is not valid.
tried cstr, tostring etc still prob persists

Don't use + to concatenate in VB. Use the actual concatenation operator, i.e. &. The problem is that you are adding a String and a number so the system has to decide which one will be converted. You assume the number but it's actually the String. That String obviously can't be converted to a number so it fails, exactly as the error message is telling you. If you want to concatenate then use the right operator and there's no confusion.

Related

Managing Blank field from Linq Query

I am writing a method in VB.Net that runs a LINQ query on my database, and puts the information from the query into textboxes on a form.
Public Sub OpenPartWindow(ByVal partNumber As String)
Using dbContext As New DB_LINQDataContext
Dim query = (From p In dbContext.Parts
Join ppl In dbContext.Part_Price_Logs On p.Part_ID Equals ppl.Part_ID
Where p.Part_Number = partNumber
Select p.Part_Number, p.Part_Description, p.Part_Information, p.Supplier.Supplier_Name, _
p.Part_Manufacturer.Manufacturer_Name, p.Part_Subcategory.Part_Category.Category_Description, _
p.Part_Subcategory.Subcategory_Description, ppl.Cost_Per_Unit, ppl.Discount_Percentage).First()
MessageBox.Show(query.ToString())
txtPartNum.Text = query.Part_Number.ToString()
txtSupplier.Text = query.Supplier_Name.ToString()
txtManufacturer.Text = query.Manufacturer_Name.ToString()
txtPrice.Text = query.Cost_Per_Unit.ToString()
txtDiscount.Text = query.Discount_Percentage.ToString()
txtDescription.Text = query.Part_Description.ToString()
txtInfo.Text = query.Part_Information.ToString()
Me.Show()
End Using
End Sub
The issue I am having right now is with the last field, the txtInfo TextBox. You see the Part_Information field on the database allows NULL values. So when I go to fill the field when the field is null I am getting a NullReferenceException, which is understandable. However I cannot find a way to get around this exception.
I've tried:
If Not IsNothing(query._Part_Information.ToString()) Then
As well as
If query.Part_Information.Length > 0 Then
As If statements to run through first. But I keep getting the error each time. So I am confused on how I am suppose to deal with this error.
You can use either of the following options:
txtInfo.Text = String.Format("{0}", query.Part_Information)
txtInfo.Text = $"{query.Part_Information}" → $ - String Interpolation
txtInfo.Text = query.Part_Information?.ToString() → ?. - Null Conditional Operator
If query.Part_Information is null, the first two expressions result in Sting.Empty and the last one result in Nothing.

VBA Access find and merge coding

Thanks for the assistance on my previous question.
My new request is still on database, however, I now require to find and merge the data and now I'm getting errors again, and I think it is because of the way it is done.
Though, I was thinking if I import the data normal from other tables it should work, however, this caused another issues where the data did not matched up correctly.
As such, I require to do a find and merge type approach, so that it find SKU numbers then the Item Description and import the percentage returns on that items.
The SKU in some reports are newer SKU and as such it will need to add the field.
My code approach that I did is as follows:
Dim myR As Recordset
Dim myR2 As Recordset
Set myR = Nothing
Set myR2 = Nothing
Set myR = CurrentDb.OpenRecordset("[Nov 2015 Clicks Returns]", dbOpenDynaset)
Set myR2 = CurrentDb.OpenRecordset("[Clicks Returns]", dbOpenDynaset)
Do Until myR.EOF = True
myR2.Find ("[SKU]=" & myR!Sku)
If myR2.NoMatch = True Then
myR2.AddNew
myR2![Sku] = myR![Sku]
myR2![Item Description] = myR![Item Description]
myR2![Nov 2015 FIN YTD TY % Returns] = myR![F23]
myR2.Update
Else
myR2.Edit
myR2![Nov 2015 FIN YTD TY % Returns] = myR2![Nov 2015 FIN YTD TY % Returns] & "" & myR![F23]
myR2.Update
End If
myR.MoveNext
Loop
Set myR = Nothing
Set myR2 = Nothing
My previous import code that I received last time:
Dim strSQL As String
strSQL = "INSERT INTO [Clicks Returns] " & _
"(SKU, [Item Description], [Oct 2015 FIN YTD TY % Returns]) " & _
"SELECT Sku, [Item Description], F21 FROM [Oct 2015 Clicks Returns];"
DoCmd.RunSQL strSQL
Thank you for taking the time to overlook with my problem and also for the time in answering it. Much appreciated :D

using wildcard to find records of a textbox linked to a query

I have a Textbox that requires me to type a number and then click a button to find the related values. but now what i need it to do is if i type 3 numbers Ex."123" it will return all the numbers that are related to any record starting with "123". I'm not sure if it's possible. and i'm using the following code but when i run it it gives me a type missmatch.
Private Sub Command35_Click()
If IsNull(Me.Text22.Value) = True Then
MsgBox "You need to enter a reference number"
ElseIf IsNull(Me.Text22.Value) = False Then
Me.List28.RowSource = "SELECT dbo_Typesofmaterial.[MATERIAL NAME], dbo_Inventory.[REFF NUMBER], dbo_Whse.[NAME], dbo_Inventory.NO_IN, dbo_Inventory.[POSITION], dbo_Inventory.[PO NO], dbo_Inventory.[REF NO2], dbo_Suppliers.SUPPLIERID, dbo_Inventory.DATE, dbo_Inventory.MATTYPE FROM (dbo_OrderDetails INNER JOIN (((dbo_Inventory INNER JOIN dbo_PurchaseOrders ON dbo_Inventory.[PO NO] = dbo_PurchaseOrders.[PO NO]) INNER JOIN dbo_Suppliers ON dbo_PurchaseOrders.ID = dbo_Suppliers.ID) INNER JOIN dbo_Typesofmaterial ON dbo_Inventory.MATTYPE = dbo_Typesofaterial.ID) ON dbo_OrderDetails.[REFF NUMBER] = dbo_Inventory.[REFF NUMBER]) INNER JOIN dbo_Whse ON dbo_Inventory.[FINAL DESTN ] = dbo_Whse.[WHSE NO] WHERE (((dbo_Inventory.[REF NO2])= " * " & [Forms]![Ref No Locator]![Text22] & " * " ));"
Else
End If
End Sub
Your offending criteria is as follows:
WHERE (((dbo_Inventory.[REF NO2])= " * " & [Forms]![Ref No Locator]![Text22] & " * " ))
I think you have a couple of problems. First, you need to use Like rather than = for a wildcard search. Second, dbo_Inventory.[REF NO2] is a numeric field and you are trying to use a string as the criteria value. Hence you need to use CStr to convert the numeric field to a string to match the criteria being used. In addition you don't need the wildcard at the start as you are matching the first 3 characters.
WHERE (((CStr(dbo_Inventory.[REF NO2])) Like '" & [Forms]![Ref No Locator]![Text22] & "*'" ))

VB6 syntax problem, "no current record" error

I am writing an app in vb6 using sql server 2005. here is my current code.
Dim Sqlstring As String
Dim rstCurrentTicket As Recordset
Sqlstring = "Select SubmiterName, LastViewDate, Department, Description, Urgency, SubmitDate, ResolvedDate from TroubleTickets where Title ='" + Trim(TicketComboBox.Text) + "'"
Set rstCurrentTicket = cnnSel.OpenRecordset(Sqlstring)
NameText.Text = rstCurrentTicket!SubmiterName
DeptText.Text = rstCurrentTicket!Department
Me.DescriptionText = rstCurrentTicket!Description
Me.UrgencyText = rstCurrentTicket!Urgency
when I run this code i recieve an error code saying:
"Run-Time error: '3021'"
"no current record"
and it highlights this line of code:
NameText.Text = rstCurrentTicket!SubmiterName
any suggestions of how to fix this?
Your recordset has no results. You can check for this as follows:
If Not rstCurrentTicket.EOF Then
NameText.Text = rstCurrentTicket!SubmiterName
DeptText.Text = rstCurrentTicket!Department
Me.DescriptionText = rstCurrentTicket!Description
Me.UrgencyText = rstCurrentTicket!Urgency
End If
EOF = End Of File = the end of the recordset has been reached.
Keith is exactly right, but I wanted to give a little more detail
For ADO and DAO, you have a Begin-of-File marker (BOF)and an End-of-File marker(EOF). The records are returned like this
[BOF]
[Record one] <-
[Record two]
...
[Record n]
[EOF]
The arrow points to where the cursor is. The cursor points to which record in the record set that is returned.
When no records are returned, you get this
[BOF]
[EOF]
So, if both flags are set, there are no records. If EOF is set, either you have no records, or you've moved past the last record. (You move that cursor to the next record by this command.)
rstCurrentTicket.MoveNext
You can also check by
If (rstCurrentTicket.EOF and rstCurrentTicket.BOF) Then
msgbox "There were no Trouble Tickets found."
Else
'Do something here.
End If

Check if email exists

I have a classic ASP page with some code to check if an email exists in the table as follows;
<%
'' //Check the submitted email against existing ones in the database
set CmdCheckEmail = server.CreateObject("ADODB.Command")
CmdCheckEmail.ActiveConnection = MM_dbconn_STRING
CmdCheckEmail.CommandText = "SELECT COUNT(ReferredEmail) AS 'CountEmail' FROM TenantReferral WHERE ReferredEmail = '" & Request("Email") & "'"
Response.Write(CmdCheckEmail.CommandText)
CmdCheckEmail.CommandType = 1
CmdCheckEmail.CommandTimeout = 0
CmdCheckEmail.Prepared = true
CmdCheckEmail.Execute()
countEmail = CmdCheckEmail("CountEmail")
set CmdCheckEmail = nothing
conn.close
set conn = nothing
If(countEmail >= 1) Then
Message = Message & "<p>This email address has already been referred.</p>"
End If
%>
However, the page is reporting the following error;
SELECT COUNT(ReferredEmail) AS 'CountEmail' FROM TenantReferral WHERE ReferredEmail = 'test#xyz.com'
ADODB.Command error '800a0cc1'
Item cannot be found in the collection corresponding to the requested name or ordinal.
/default2.asp, line 19
Line 19 is as follows;
countEmail = CmdCheckEmail("CountEmail")
The email does exist in the table and the table simply has the following columns; ReferredEmail and ReferredCode
I wondered if anyone might be able to shed any light on this error?
Thank you.
Note sure what database you are using but try changing your sql to:
SELECT COUNT(ReferredEmail) AS CountEmail FROM TenantReferral WHERE ReferredEmail = 'test#xyz.com'
Then change
CmdCheckEmail.Execute()
countEmail = CmdCheckEmail("CountEmail")
to
set rs = CmdCheckEmail.Execute()
countEmail = rs("CountEmail")
Also, you have a SQL injection issue with that query. You should be using parameterized queries.
CmdCheckEmail("CountEmail") tries to access the default member of the Command object, which is the parameters collection. However, you don't want to access a parameter but a field of the resulting recordset.
Try this (not tested):
Set rs=CmdCheckEmail.Execute()
countEmail = rs("CountEmail")
Apart from that, beware: This line:
CmdCheckEmail.CommandText = "SELECT COUNT(ReferredEmail) AS 'CountEmail' FROM TenantReferral WHERE ReferredEmail = '" & Request("Email") & "'"
is vulnerable to an SQL injection attack.
Never embed literal strings into SQL statement; use parameters instead. (In this case, you would do that using the Command.Parameters collection.)