I get an error:
when I execute this code:
Private Sub EditMethodAdd_Click()
MsgBox ("Add Click")
Dim rs As ADODB.Recordset
Dim introw
Dim strState As String
Dim strsql1 As String
Dim strsql2 As String
Dim all As String
Dim strConn As String
Dim conn As ADODB.Connection
MsgBox ("EditM1.Value:" & EditM1.value)
strConn = "DRIVER=SQL Server;SERVER=CHU-AS-0004;DATABASE=RTC_LaplaceD_DEV;Trusted_Connection=Yes;"
strsql1 = " INSERT INTO dbo.Method(MethodID, MethodClass, Category, Description, Description2, MSA, ReqType, Equipment, Location, Spec1, Spec2, Spec3, Spec4, Spec5, Spec6, PilotingYN) "
strsql2 = " VALUES( " & EditM1.value & ", Piloting, " & EditM3.value & ", Null, Null, Null, Null," & EditM2.value & ", " & EditM4.value & ", " & EditM5.value & ", " & EditM6.value & ", " & EditM7.value & ", " & EditM8.value & ", " & EditM9.value & ", " & EditM10.value & ", " & Null & " )"
all = strsql1 & strsql2
MsgBox ("ALL" & all)
Set conn = New ADODB.Connection
conn.Open strConn
Set rs = New ADODB.Recordset
rs.Open all, conn
MsgBox ("Insert Success")
EditMethodList.Requery
conn.Close
Set rs = Nothing
Set conn = Nothing
MsgBox "Data has been updated"
EditMethodList.Requery
End Sub
Is there anyone who can solve this problem?
I think I made the query fine, but this error keeps annoying me.
Any comments would be greatly thankful.
The MsgBox("All" & all) shows this results.
As your MessageBox shows, you try to insert incorrect value 9.4.5V(LCO)+ICPqwer.
What is the data type of MethodID?
If it's varchar and contains +ICPqwer as part of the string, you
should pass the whole string quoted, like this
'9.4.5V(LCO)+ICPqwer'
if it's a string but has a format 9.4.5V(LCO)+ some other string
(that is contained in ICPqwer), use '9.4.5V(LCO)' + ICPqwer
if ICPqwer is a number, use this one: '9.4.5V(LCO)' + cast(ICPqwer
as varchar(100))
Besides, all the other values seem also to be strings and should be quoted as well:
'Piloting', 'Internal Analysis', ...
The last thing: what are the "empty" values that you are passing in like ,,,?
Pass the NULL explicitely, or if they are empty strings, pass them as ''
Related
This question already has an answer here:
What are the limits for ADO data types?
(1 answer)
Closed 3 years ago.
I can't figure out how to retrieve long text (>8kb) from a SQL Server field using an ADODB connection through Excel VBA. My method returns a garbage string.
I can successfully upload a field with >8kb data length using a parameterized query as in the following code:
Public Sub TestLongParamUploadQuery()
Dim conn As ADODB.Connection
Dim cmd As ADODB.Command
Dim param As ADODB.Parameter
Dim rs As ADODB.Recordset
Query = "INSERT INTO MYTABLE ([Long_Text], [Table_Index]) VALUES (?, ?);"
Set conn = New ADODB.Connection
conn.ConnectionString = connStr
On Error GoTo connerror
conn.Open
Set cmd = New ADODB.Command
With cmd
.ActiveConnection = conn
.CommandText = Query
.CommandType = adCmdText
Set Pm = .CreateParameter("long_text", adLongVarWChar, adParamInput, 20000)
Pm.Value = Replace("THIS IS A REALLY LONG TEXT STRING " & Space(8000) & "THIS IS A REALLY LONG TEXT STRING", " ", ".")
.Parameters.Append Pm
Set Pm = .CreateParameter("table_index", adVarChar, adParamInput, 32)
Pm.Value = "MYFAKERECORD"
.Parameters.Append Pm
Set rs = .Execute
End With
connerror:
If Err.Number <> 0 Then
Msg = "Error # " & str(Err.Number) & " was generated by " _
& Err.Source & Chr(13) & "Error Line: " & Erl & Chr(13) & Err.Description
MsgBox Msg, , "Error", Err.HelpFile, Err.HelpContext
End If
conn.Close
End Sub
But when I attempt to retrieve the data via a SELECT statement, the data comes back garbled.
Public Sub TestLongParamDownloadQuery()
Dim conn As ADODB.Connection
Dim cmd As ADODB.Command
Dim param As ADODB.Parameter
Dim rs As ADODB.Recordset
Query = "SELECT * FROM MYTABLE WHERE Table_Index='MYFAKERECORD';"
Set conn = New ADODB.Connection
conn.ConnectionString = connStr
On Error GoTo connerror
conn.Open
Set cmd = New ADODB.Command
With cmd
.ActiveConnection = conn
.CommandText = Query
.CommandType = adCmdText
End With
Set rs = cmd.Execute()
Do Until rs.EOF = True
For i = 0 To rs.Fields.Count - 1
If Not IsNull(rs.Fields.Item(i)) Then
Debug.Print ("field '" & rs.Fields(i).Name & "' length: " & Len(rs.Fields.Item(i)) & "; value: '" & rs.Fields.Item(i) & "'")
End If
Next
rs.MoveNext
Loop
connerror:
If Err.Number <> 0 Then
Msg = "Error # " & str(Err.Number) & " was generated by " _
& Err.Source & Chr(13) & "Error Line: " & Erl & Chr(13) & Err.Description
MsgBox Msg, , "Error", Err.HelpFile, Err.HelpContext
End If
conn.Close
End Sub
The data is successfully making it into the database. I'm able to open and see it in SQL Server Management Studio.
However. The Debug.Print output from my download looks like the following
field 'Long_Text' length: 8067; value: ' MYFAKERECORD ? ?%0?? ?%0?? ? ? ? ? ?
'
field 'Table_Index' length: 12; value: 'MYFAKERECORD'
Note that the length appears to be correct. It's not merely an issue in printing in the immediate window of the Excel VBA IDE. When I write the data to an excel cell via the macro, the cell contains '``' after upload.
I've tried the upload with the parameter for Unicode adLongVarWChar and plaintext adLongVarChar. Both appear to place data correctly in the database. Both come back as broken text from the select statement.
What is the appropriate way to download and interrogate long text via adodb?
EDIT I did find this thread which notes a fundamental limitation that ADO cannot interpret nvarchar(max) type. The proposed solution of CAST'ing the variable to nvarchar(20000) will not work for me because the upward limit for CAST is 8000 characters. How can I transfer data from a field GREATER than 8kb to Excel VBA?
This answer was drawn from the post What are the limits for ADO data types?
The solution as is to:
Cast the desired fields as text.
Retrieve the actual data from the record set using string = rs.Fields(0).GetChunk(rs.Fields(0).ActualSize)
Incorporating into my code it looks like:
Public Sub TestLongParamDownloadQuery()
Dim conn As ADODB.Connection
Dim cmd As ADODB.Command
Dim param As ADODB.Parameter
Dim rs As ADODB.Recordset
Query = "SELECT * FROM MYTABLE WHERE Table_Index='MYFAKERECORD';"
Set conn = New ADODB.Connection
conn.ConnectionString = connStr
On Error GoTo connerror
conn.Open
Set cmd = New ADODB.Command
With cmd
.ActiveConnection = conn
.CommandText = Query
.CommandType = adCmdText
End With
Set rs = cmd.Execute()
Do Until rs.EOF = True
For i = 0 To rs.Fields.Count - 1
If Not IsNull(rs.Fields.Item(i)) Then
If rs.Fields.Item(i).Name = "Long_Text" Then
Debug.Print(rs.Fields(i).GetChunk(rs.Fields(i).ActualSize))
End If
Debug.Print ("field '" & rs.Fields(i).Name & "' length: " & Len(rs.Fields.Item(i)) & "; value: '" & rs.Fields.Item(i) & "'")
End If
Next
rs.MoveNext
Loop
connerror:
If Err.Number <> 0 Then
Msg = "Error # " & str(Err.Number) & " was generated by " _
& Err.Source & Chr(13) & "Error Line: " & Erl & Chr(13) & Err.Description
MsgBox Msg, , "Error", Err.HelpFile, Err.HelpContext
End If
conn.Close
End Sub
I have some problem when inserting data to database.
I am using mssql.
Private Sub EditMethodAdd_Click()
Dim rs As ADODB.Recordset
Dim introw
Dim strState As String
Dim strsql1 As String
Dim strsql2 As String
Dim all As String
Dim strConn As String
Dim conn As ADODB.Connection
MsgBox ("EditM1.Value:" & EditM1.value)
strConn = "DRIVER=SQL Server;SERVER=CHU-AS-0004;DATABASE=RTC_LaplaceD_DEV;Trusted_Connection=Yes;"
strsql1 = " INSERT INTO dbo.Method(MethodID, MethodClass, Category, Description, Description2, MSA, ReqType, Equipment, Location, Spec1, Spec2, Spec3, Spec4, Spec5, Spec6, PilotingYN) "
strsql2 = " VALUES(EditM1.value, 'Piloting', EditM3.value, Null, Null, Null, Null, EditM2.value, EditM4.value, EditM5.value, EditM6.value, EditM7.value, EditM8.value, EditM9.value, EditM10.value, Null )"
all = strsql1 & strsql2
MsgBox ("ALL" & all)
Set conn = New ADODB.Connection
conn.Open strConn
Set rs = New ADODB.Recordset
rs.Open all, conn
MsgBox ("Insert Success")
EditMethodList.Requery
conn.Close
Set rs = Nothing
Set conn = Nothing
MsgBox "Data has been updated"
EditMethodList.Requery
End Sub
When I check the value for EditM1 by using MsgBox, it shows correct.
But I got error message like this.
Is there anyone who can solve this problem?
Thank you in advance.
Delete the lines:
strsql1 = ...
strsql2 = ...
all = strsql1 & strsql2
and write this instead
all = "INSERT INTO dbo.Method(MethodID, MethodClass, Category, Description, Description2, MSA, ReqType, Equipment, Location, Spec1, Spec2, Spec3, Spec4, Spec5, Spec6, PilotingYN) "
all = all & "VALUES(" & EditM1.value & ", 'Piloting'," & EditM3.value & ", Null, Null, Null, Null," & EditM2.value & "," & EditM4.value & ","
all = all & EditM5.value & "," & EditM6.value & "," & EditM7.value & "," & EditM8.value & "," & EditM9.value & "," & EditM10.value & ", Null )"
If you insert EditM1.value into doublequotes, as you did, VBA read it as a string and it does not refer to its value. You need to concatenate string and values with & to create your query.
You're putting the literal value "EditM1.value" into your SQL: you should instead be sending the Value of the control:
strsql2 = " VALUES(" & EditM1.value & ", 'Piloting', " & _
EditM3.value & ", Null,..." 'etc
If any of the values being sent are not numeric then they should be wrapped in single quotes.
Can someone please let me know what is wrong with this code? I have checked all lines for misspellings - this isnt the issue. All tables and queries are written as they exist in the db. Any help is appreciated.
Private Sub LoadArray()
'---------------------------
'---------------------------
'This procedure loads text into the 3rd column of the array
'---------------------------
'---------------------------
Dim db As DAO.Database
Dim rs As DAO.Recordset
Dim rsFiltered As DAO.Recordset
Dim strSQL As String
Dim i As Integer
strSQL = "SELECT tblProperties.Name, tbl1OpportuniyType.Type, qryPropertiesALLTypesALLTbls.TotalUnits, " _
& "qryPropertiesALLTypesALLTbls.EventStartTimeEachDay, qryPropertiesALLTypesALLTbls.EventEndTimeEachDay, " _
& "qryPropertiesALLTypesALLTbls.EventStartDate, qryPropertiesALLTypesALLTbls.EventStopDate, " _
& "qryPropertiesALLTypesALLTbls.TechOpsGroup, qryPropertiesALLTypesALLTbls.TechOpsResource " _
& "FROM tbl1OpportuniyType RIGHT JOIN (qryPropertiesALLTypesALLTbls INNER JOIN tblProperties ON qryPropertiesALLTypesALLTbls.[PropertyComplex_ID] = tblProperties.[PropertyComplex_ID]) ON tbl1OpportuniyType.[OpportunityType_ID] = tblProperties.OpportunityType " _
& "WHERE (((qryPropertiesALLTypesALLTbls.EventStartDate) Is Not Null));"
'Debug.Print strSQL
Set db = CurrentDb
Set rs = db.OpenRecordset(strSQL)
'This line ensures that the recordset is populated
If Not rs.BOF And Not rs.EOF Then
'Loops through the Array using dates for the filter
For i = LBound(myArray) To UBound(myArray)
If myArray(i, 1) Then
'Filters recordset with array dates
rs.Filter = "[EventStartDate]= " & myArray(i, 0)
'Open up new recordset based on filter
Set rsFiltered = rs.OpenRecordset
'Loop through new recordset
Do While (Not rsFiltered.EOF)
'Adds text to the 3rd column of the array
myArray(i, 2) = myArray(i, 2) & vbNewLine _
& rsFiltered!Type & " - " & vbNewLine _
& rsFiltered!Name & " " _
& rsFiltered!EventStartDate & " - " _
& rsFiltered!EventStopDate & " " _
& rsFiltered!EventStartTimeEachDay & " - " _
& rsFiltered!TechOpsGroup & " " _
& rsFiltered!TechOpsResource & " " _
& vbNewLine
rsFiltered.MoveNext
Loop
End If
Next i
End If
rsFiltered.Close
rs.Close
'Sets objects to nothing
Set rsFiltered = Nothing
Set rs = Nothing
Set db = Nothing
End Sub
It isn't clear where myArray comes from, but the filter needs an adjustment to convert the date value to a string expression:
rs.Filter = "[EventStartDate] = #" & Format(myArray(i, 0), "yyyy\/mm\/dd") & "#"
So, I am trying to read in a text file using VB.NET and add the values of each line into a SQL Server database table. The code I have this far reads in the first line but keeps trying to read in the same line and fails. It adds the first, but like I stated it fails after the first one. I am quite sure the problem is in my loop and/or mysplit() array values. Any help in the right direction would be greatly appreciated. Thank you
Public Sub addTxtMember()
'Dim fileName As String
' fileName = Application.StartupPath + "c:\users\james needham\documents\visual studio 2013\projects\textfiletutorial1\textfiletutorial1\textfile1.txt"
Dim fileName As Integer = FreeFile()
'If File.Exists(fileName) Then
'Dim iofile As New StreamReader(fileName)
FileOpen(fileName, "TextFile1.txt", OpenMode.Input)
Dim ioline As String
'Dim iolines() As String
Dim eID, fName, lName, email, phone
Dim i As Integer = 0
ioline = LineInput(fileName)
'Do Until EOF(fileName)
While Not ioline = ""
' Dim endsplit = Split(ioline, "")
Dim mysplit = Split(ioline, ",")
eID = mysplit(0)
fName = mysplit(1)
lName = mysplit(2)
phone = mysplit(3)
email = mysplit(4)
' try
Dim strInsert As String = "INSERT INTO Employees1 (eID, fName, lName, phone, email) " & _
"VALUES (" & _
"'" & eID & "'," & _
"'" & fName & "', " & _
"'" & lName & "', " & _
"'" & phone & "', " & _
"'" & email & "')"
'MsgBox(strInsert)
SQLCon.Open()
SQLCmd = New SqlCommand(strInsert, SQLCon)
'has to be non when inserting, updating, or deleting
SQLCmd.ExecuteNonQuery()
SQLCon.Close()
' Catch ex As Exception
'MsgBox(ex.Message)
'End Try
End While
FileClose(fileName)
'Else
'MsgBox("fILE NOT FOUND")
' FileClose(fileName)
'End If
End Sub
The following comment in no way implies I believe this program will work -- it is has many errors but to answer your question about only seeing one line show up:
add the line
ioline = LineInput(fileName)
before the
END WHILE
You asked for a nudge regarding your loop...
For Each line As String In (New StreamReader("TextFile1.txt")).ReadToEnd.Split(ControlChars.CrLf)
'examine the value of line and parse it into the DB here
Next
I can update an SQL table via Excel VBA except the date. The value comes through as 1900-01-01 or in some cases where I have played with the format it is shown as 1900-01-28.
It is a simple setup just for testing.
One Table with two columns CellText and CellDate, both getting their values from a cell range.
The value expected for CellText is 'Some Text'
The value expected for CellDate is 24/03/2015
Sub UpdateTable()
Dim cnn As ADODB.Connection
Dim uSQL As String
Dim strText As String
Dim strDate As Date
strText = ActiveSheet.Range("b4").Value
strDate = Format(ActiveSheet.Range("c4").Value, "dd/mm/yyyy")
Set cnn = New Connection
cnnstr = "Provider=SQLOLEDB; " & _
"Data Source=ServerName; " & _
"Initial Catalog=DbName;" & _
"User ID=UserName;" & _
"Trusted_Connection=Yes;"
cnn.Open cnnstr
uSQL = "INSERT INTO tbl_ExcelUpdate (CellText,CellDate) VALUES ('" & strText & "', " & strDate & ")"
Debug.Print uSQL
cnn.Execute uSQL
cnn.Close
Set cnn = Nothing
Exit Sub
End Sub
My Debug value is
INSERT INTO tbl_ExcelUpdate (CellText,CellDate) VALUES ('Some Text ', 24/03/2015)
My CellDate format in table is datetime.
Looks like you are missing single quotes on either side of the date.
INSERT INTO tbl_ExcelUpdate (CellText,CellDate) VALUES ('Some Text ', 24/03/2015)
Should be
INSERT INTO tbl_ExcelUpdate (CellText,CellDate) VALUES ('Some Text ', '24/03/2015')
Use CDate function to convert string formated date to date type
Sub UpdateTable()
Dim cnn As ADODB.Connection
Dim uSQL As String
Dim strText As String
Dim strDate As Date
strText = ActiveSheet.Range("b4").Value
strDate = Format(ActiveSheet.Range("c4").Value, "dd/mm/yyyy")
Set cnn = New Connection
cnnstr = "Provider=SQLOLEDB; " & _
"Data Source=ServerName; " & _
"Initial Catalog=DbName;" & _
"User ID=UserName;" & _
"Trusted_Connection=Yes;"
cnn.Open cnnstr uSQL = "INSERT INTO tbl_ExcelUpdate (CellText,CellDate) VALUES ('" & strText & "', " & CDate(strDate) & ")"
Debug.Print uSQL
cnn.Execute uSQL
cnn.Close
Set cnn = Nothing
Exit Sub
End Sub
you have to correct the strDate = Format(ActiveSheet.Range("c4").Value, "dd/mm/yyyy") to
strDate = Format(ActiveSheet.Range("c4").Value, "dd-mm-yyyy").
Then you have to put quotes:
uSQL = "INSERT INTO tbl_ExcelUpdate (CellText,CellDate) VALUES ('" & strText & "', '" & strDate & "')"