How to check Table exists in MS Access through VBscript - vbscript

I have a vbscript that trying to create the table in MS Access DB, but i want to make it like if the table is exists, then it will direct proceed to enter data without need of creating the table.
What can i do to check the existing of the table is created or not?
My code as below, it will not proceed to insert data if the table is already exists.
'Constants
'Const adOpenStatic = 3
Const adOpenDynamic = 2
Const adLockOptimistic = 3
Const adCmdTable = &H0002
Set objConn = CreateObject("ADODB.Connection")
Set objRecordSet = CreateObject("ADODB.Recordset")
'Connect Primary DB
connStr = "Provider=Microsoft.Jet.OLEDB.4.0; Data Source=" & "C:\AIS_Workfolder\Reference\DB\" & "AIS_DataDB.mdb"
'Open Connection
objConn.open connStr
'Create table
objConn.Execute "CREATE TABLE " & "test_table" & "(" & _
"[ID] COUNTER ," & _
"[Field1] TEXT(255) ," & _
"[Field2] TEXT(255) ," & _
"[Field3] TEXT(255) ," & _
objRecordSet.Open "test_table", objConn, adOpenDynamic, adLockOptimistic, adCmdTable
objRecordSet.AddNew
objRecordSet("Field1").value = "testing123"
objRecordSet("Field2").value = "testing123"
objRecordSet("Field3").value = "testing123"

Or like this one:
Function TableExists(strTableName)
Dim RStmp
TableExists = true
on error resume next
RStmp=Conn.Execute("SELECT * FROM ["&strtablename&"]")
If Err.Number <> 0 Then TableExists=false
on error goto 0
End Function

Use a function like this:
If TableExists("test_table") Then
' Take action here
Else
' Create table here
End If
Function TableExists(TabletoFind)
TableExists = False
Set adoxConn = CreateObject("ADOX.Catalog")
Set objConn = Server.CreateObject("ADODB.Connection")
objConn.Open(ConnStr)
adoxConn.ActiveConnection = objConn
IsThere = False
For Each Table in adoxConn.Tables
If LCase(Table.Name) = LCase(TabletoFind) Then
IsThere = True
Exit For
End If
Next
objConn.Close
Set objConn = Nothing
Set adoxConn = Nothing
If IsThere Then TableExists = True
End Function

Related

adding data to oracle database in vb6

I have a problem adding data oracle database,it's show me this message(" https://ufile.io/lzpuj ") Run-time ORA-00904:"EMPCODE": invalid identifier.
This is Cody:
Dim connEmp As ADODB.Connection
Dim rsEmp As ADODB.Recordset
Private Sub Command1_Click()
Set rsEmp = New ADODB.Recordset
rsEmp.Open "select * from tablebooks where empcode = '" & Text1.Text & "'",
connEmp, adOpenKeyset, adLockReadOnly, adCmdText
If rsEmp.RecordCount <> 0 Then
MsgBox " ! åÐÇ ÇáßÊÇÈ ãæÌæÏ ÈÇáÝÚá "
rsEmp.Close
Set rsEmp = Nothing
Exit Sub
Else
Set rsEmp = New ADODB.Recordset
rsEmp.Open "select * from tablebooks where empcode = '" & Text1.Text & "'",
connEmp, adOpenKeyset, adLockPessimistic, adCmdText
rsEmp.AddNew
rsEmp!Book_no = Val(Trim(Text1.Text))
rsEmp!Book_name = Trim(Text2.Text)
rsEmp!Author_name = Trim(Text10.Text)
rsEmp!Edition_no = Val(Trim(Text3.Text))
rsEmp!Publisher_place = Trim(Text11.Text)
rsEmp!Part_no = Val(Trim(Text5.Text))
rsEmp!Book_cost = Trim(Text6.Text)
rsEmp!Place_book = Trim(Text7.Text)
rsEmp!Note = Trim(Text9.Text)
rsEmp!Date_publishing = DTPicker1.Value
rsEmp!Subject = Trim(Combo4.Text)
rsEmp!State = Trim(Combo4.Text)
rsEmp.Update
connEmp.Execute "commit"
rsEmp.Close
Set rsEmp = Nothing
Label11.Visible = True
Label11 = " ! ÊãÊ ÇáÅÖÇÝÉ ÈäÌÇÍ "
End If
End Sub
First make sure empcode is exactly the right column name.
Then fix your code. You have two big issues:
It's crazy-vulnerable to Sql Injection attacks.
It tries to re-open the same command on the same connection in the ELSE block for no reason.
The exact fix for #1 depends on which provider you are using (Ole vs Odbc), but this link might help:
Call a parameterized Oracle query from ADODB in Classic ASP
For #2, this is somewhat better:
Dim connEmp As ADODB.Connection
Dim rsEmp As ADODB.Recordset
Private Sub Command1_Click()
Set rsEmp = New ADODB.Recordset
'TODO: Use parameterized query here!
rsEmp.Open "select * from tablebooks where empcode = #empcode '" & Text1.Text & "'",
connEmp, adOpenKeyset, adLockReadOnly, adCmdText
If rsEmp.RecordCount <> 0 Then
MsgBox " ! åÐÇ ÇáßÊÇÈ ãæÌæÏ ÈÇáÝÚá "
rsEmp.Close
Set rsEmp = Nothing
Exit Sub
End If
rsEmp.AddNew
rsEmp!Book_no = Val(Trim(Text1.Text))
rsEmp!Book_name = Trim(Text2.Text)
rsEmp!Author_name = Trim(Text10.Text)
rsEmp!Edition_no = Val(Trim(Text3.Text))
rsEmp!Publisher_place = Trim(Text11.Text)
rsEmp!Part_no = Val(Trim(Text5.Text))
rsEmp!Book_cost = Trim(Text6.Text)
rsEmp!Place_book = Trim(Text7.Text)
rsEmp!Note = Trim(Text9.Text)
rsEmp!Date_publishing = DTPicker1.Value
rsEmp!Subject = Trim(Combo4.Text)
rsEmp!State = Trim(Combo4.Text)
rsEmp.Update
connEmp.Execute "commit"
rsEmp.Close
Set rsEmp = Nothing
Label11.Visible = True
Label11 = " ! ÊãÊ ÇáÅÖÇÝÉ ÈäÌÇÍ "
End Sub

VBScript \ Active Directory Searched by displayname and received 2 of the same

I have my script to search by displayname and return the userid, which works fine.
but when I encounter a displayname that has 2 entries in AD i.e.
pavle stojanovic - he is from company 1
pavle stojanovic - he is from company 2
the userid doesnt get displayed because the script doesnt know what to do ?
how do i over come this ? if I get a return of 2 or more I'd like to say in the output hey i found the same name twice etc.. here are the userids and companies for both.
If you want to see the script its below...
strFile = objFSO.GetParentFolderName(Wscript.ScriptFullName) & "\users.xls"
Set objWorkbook = objExcel.Workbooks.Open(strFile)
objWorkbook.Activate
objExcel.Visible = False
intRow = 2 ' starts reading file at line 2
' this part runs a loop through the excel file reading each userid and getting data requested.
' ---------------------------------------------------------------------------------------------
Do Until objExcel.Cells(intRow,1).Value = ""
ExcelRow = objExcel.Cells(intRow, 1)
Call GetOU ' calling sub to search
intRow = intRow + 1
Loop
' This section just formats the excel file to widen the columns
' --------------------------------------------------------------
Set objRange = objExcel.Range("A1")
objRange.Activate
Set objRange = objExcel.ActiveCell.EntireColumn
objRange.AutoFit()
Set objRange = objExcel.Range("B1")
objRange.Activate
Set objRange = objExcel.ActiveCell.EntireColumn
objRange.AutoFit()
Set objRange = objExcel.Range("C1")
objRange.Activate
Set objRange = objExcel.ActiveCell.EntireColumn
objRange.AutoFit()
Set objRange = objExcel.Range("D1")
objRange.Activate
Set objRange = objExcel.ActiveCell.EntireColumn
objRange.AutoFit()
objExcel.ActiveWorkbook.Save
objExcel.Quit
' Sub to get Details for user
' ----------------------------
Sub GetOU
On Error Resume Next
Set objRootDSE = GetObject("LDAP://RootDSE")
strDomain = objRootDSE.Get("DefaultNamingContext")
Set objConnection = CreateObject("ADODB.Connection")
objConnection.Provider = "ADsDSOObject"
objConnection.Open "Active Directory Provider"
Set objCommand = CreateObject("ADODB.Command")
Set objCommand.ActiveConnection = objConnection
objCommand.Properties("Size Limit") = 100000
objCommand.Properties("Searchscope") = 2
objCommand.CommandText = "SELECT distinguishedName FROM 'LDAP://" & _
strDomain & _
"' WHERE objectCategory='User' AND DisplayName = '" & _
ExcelRow & "'"
Set objRecordSet = objCommand.Execute
If Not objRecordSet.EOF Then
strDN = objRecordSet.Fields("distinguishedName").Value
' ###########################################################
' ###########################################################
' This is where the script does 'its thing' ...
' gets what you want.
' ------------------------------------------------
Set MyUser = GetObject ("LDAP://" & strDN)
objExcel.Cells(intRow, 3).Value = UCASE(MyUser.SamAccountName)
' ###########################################################
' ###########################################################
Else
Wscript.Echo "User Not Found: " & ExcelRow
End If
Err.Clear
End Sub
If multiple accounts are found, the Record Set will have multiple records and you'll need to loop through it. Your code currently only gets the first item in the Record Set.
Change If Not objRecordSet.EOF Then to Do While Not objRecordSet.EOF
Then
strDN = objRecordSet.Fields("distinguishedName").Value
' ###########################################################
' ###########################################################
Set MyUser = GetObject ("LDAP://" & strDN)
When inserting the users into the spreadsheet, you'll want to control the placement of the cell dynamically so the same cell isn't written over at each loop.
objExcel.Cells(intRow, 3).Value = UCASE(MyUser.SamAccountName)
At the end of processing this user, you'll use this to move to the next object (user) in the Record Set
objRecordSet.MoveNext
Then instead of End If, you'll use Loop
EDIT:
Also, instead of connecting to the object using Set MyUser = GetObject(etc), could you just use "SELECT sAMAccountName FROM... in your query then strsAMAccountName = objRecordSet.Fields("sAMAccountName") to save some memory/time?
Edit2:
I am doing this in my script.
If objRecordSet.RecordCount = 0 Then
'Things to do if not found
Exit Sub 'Then exit before entering loop
End If
Also, if the user isn't found then objRecordSet.EOF will equal True.

updating the table using recordset

I have a recordset rcdDNE. I want to update my reclamation by making some conditions with my existing recordset. But my table is not updating. Can you guys tell me where I am doing wrong?
Dim lngRecCount As Long
frmDNELoad.lblStatus.Caption = "Updating records in Reclamation Table..."
frmDNELoad.Refresh
CqDate = Format(Date, "dd/MM/yyyy")
Set rcdreclamation = New ADODB.Recordset
With rcdreclamation
.ActiveConnection = objConn
.Source = "SELECT * FROM T_DATA_reclamation"
.CursorType = adOpenDynamic
.CursorLocation = adUseClient
.LockType = adLockOptimistic
.Open
End With
rcdDNE.MoveFirst
Do Until rcdDNE.EOF
With cmdDNEFRC
.ActiveConnection = objConn
.CommandText = "update t_data_reclamation set ClaimStatus = 'C',DateClosed = 'CqDate', Audit_LastUpdated = 'CqDate', Audit_UserAdded = 'SYSTEM' where RTProvided = '" & rcdDNE("AccountNbr") & "'"
.CommandType = adCmdText
End With
rcdDNE.MoveNext
Loop
Unless its something you forgot to put in your sample code, You are missing a call to the Execute function inside your Command object's with block.
With cmdDNEFRC
.ActiveConnection = objConn
.CommandText = "update t_data_reclamation set ClaimStatus = 'C',DateClosed = 'CqDate', Audit_LastUpdated = 'CqDate', Audit_UserAdded = 'SYSTEM' where RTProvided = '" & rcdDNE("AccountNbr") & "'"
.CommandType = adCmdText
.Execute 'dont forget execution
End With
Also when writing data to the table, using Connection objects BeginTrans and CommitTrans function is recommended, just in case something has to go wrong when writing the data you don't end up with data inconsistencies.

the connection cannt be used to perform this operation. It may closed or not valid in this context error in vb6

I am trying to execute the query which stores recordset vales in sql db. when I am trying to execute that i am getting error like
the connection cannt be used to perform this operation. It may closed or not valid in this context error in vb6. Please help me to solve this issue.
' Write records to Database
frmDNELoad.lblStatus.Caption = "Loading data into database......"
Call FindServerConnection_NoMsg
Dim lngRecCount As Long
lngRecCount = 0
rcdDNE.MoveFirst
Set rcdReclamation = New ADODB.Recordset
With rcdReclamation
.ActiveConnection = objConn
.Source = "insert into t_DATA_DneFrc (RTN, AccountNbr, FirstName, MiddleName, LastName, Amount) values ('" & rcdDNE("RTN") & "', '" & rcdDNE("AccountNbr") & "', '" & rcdDNE("FirstName") & "', '" & rcdDNE("MiddleName") & "', '" & rcdDNE("LastName") & "', '" & rcdDNE("Amount") & "')"
.CursorType = adOpenDynamic
.CursorLocation = adUseClient
.LockType = adLockOptimistic
.Open cmdCommand
End With
Do Until rcdDNE.EOF
lngRecCount = lngRecCount + 1
frmDNELoad.lblStatus.Caption = "Adding record " & lngRecCount & " of " & rcdDNE.RecordCount & " to database."
frmDNELoad.Refresh
DoEvents
Call CommitNew
rcdDNE.MoveNext
Loop
frmDNELoad.lblStatus.Caption = "DNE Processing Complete."
frmDNELoad.Refresh
End Function
Sub CommitNew()
' Add records to DneFrc table
With rcdReclamation
.Requery
.AddNew
.Fields![RTN] = rcdDNE.Fields![RTN]
.Fields![AccountNbr] = rcdDNE.Fields![AccountNbr]
.Fields![FirstName] = rcdDNE.Fields![FirstName]
.Fields![MiddleName] = rcdDNE.Fields![MiddleName]
.Fields![LastName] = rcdDNE.Fields![LastName]
.Fields![Amount] = rcdDNE.Fields![Amount]
.Update
End With
End Sub
conection code
Sub InstantiateCommand_SQLText()
' Creates a command object to be used when executing SQL statements.
Set objCommSQLText = New ADODB.Command
objCommSQLText.ActiveConnection = objConn
objCommSQLText.CommandType = adCmdText
End Sub
Function FindServerConnection_NoMsg() As String
Dim rcdClientPaths As ADODB.Recordset
Dim strDBTemp As String
Const CLIENT_UPDATE_DIR = "\\PSGSPHX02\NORS\Rs\ClientUpdate\"
On Error Resume Next
' If persisted recordset is not there, try and copy one down from
' CLIENT_UPDATE_DIR. If that can't be found, create a blank one
' and ask the user for the server name.
Set rcdClientPaths = New ADODB.Recordset
' Does it already exist locally?
If FileExists_FullPath(App.Path & "\" & "t_PCD_ServerConnectionList.xml") = False Then
' Can it be retrieved from CLIENT_UPDATE_DIR
If Dir(CLIENT_UPDATE_DIR & "t_PCD_ServerConnectionList.xml") "" Then
FileCopy CLIENT_UPDATE_DIR & "t_PCD_ServerConnectionList.xml", App.Path & "\" & "t_PCD_ServerConnectionList.xml"
Else
' Creat a blank one.
With rcdClientPaths
.Fields.Append "ServerConnection", adVarChar, 250
.Fields.Append "Description", adVarChar, 50
.CursorType = adOpenDynamic
.LockType = adLockOptimistic
.CursorLocation = adUseClient
.Open
.Save App.Path & "\" & "t_PCD_ServerConnectionList.xml", adPersistXML
.Close
End With
End If
End If
' Open the recordset
With rcdClientPaths
.CursorType = adOpenDynamic
.LockType = adLockOptimistic
.CursorLocation = adUseClient
.Open App.Path & "\" & "t_PCD_ServerConnectionList.xml", , , , adCmdFile
End With
If rcdClientPaths.RecordCount 0 Then
' try each one listed
rcdClientPaths.MoveFirst
Do Until rcdClientPaths.EOF
strDBTemp = TryConnection_NoMsg(rcdClientPaths.Fields![serverconnection])
If strDBTemp "" Then
FindServerConnection_NoMsg = strDBTemp
Exit Function
End If
rcdClientPaths.MoveNext
Loop
strDBTemp = ""
End If
Do While strDBTemp = ""
If strDBTemp "" Then
strDBTemp = TryConnection_NoMsg(strDBTemp)
If strDBTemp "" Then
With rcdClientPaths
.AddNew
.Fields![serverconnection] = strDBTemp
.Update
.Save
End With
FindServerConnection_NoMsg = strDBTemp
Exit Function
End If
Else
Exit Function
End If
Loop
End Function
Function TryConnection_NoMsg(ByVal SvName As String) As String
On Error GoTo ErrHandle
' If a server was provided, try to open a connection to it.
Screen.MousePointer = vbHourglass
Set objConn = New ADODB.Connection
With objConn
.CommandTimeout = 30
.ConnectionTimeout = 30
.ConnectionString = "Provider=SQLOLEDB.1; Server=" & SvName & "; User ID=RS_Auth; Password=weLcomers_auth; Initial Catalog=NORS" ' Test
.Open
.Close
End With
Set objConn = Nothing
TryConnection_NoMsg = SvName
Screen.MousePointer = vbNormal
Exit Function
ErrHandle:
TryConnection_NoMsg = ""
Set objConn = Nothing
Screen.MousePointer = vbNormal
Exit Function
End Function
You have already closed the connection here in TryConnection_NoMsg function (?)
With objConn
.CommandTimeout = 30
.ConnectionTimeout = 30
.ConnectionString = "Provider=SQLOLEDB.1; Server=" & SvName & "; Database=NORS; User ID=RS_Auth; Password=weLcomers_auth; Initial Catalog=NORS" ' Test
.Open
.Close
I'd suspect that FindServerConnection_NoMsg is not managing to open the connection, and since it ends in NoMsg that you're not seeing the error about why the connection wasn't opened. You then go on to just use the connection without knowing that the open failed.
Post the code for FindServerConnection_NoMsg.
BTW, your question itself should have given you a clue. It specifically says that the connection can't be used, and that it may not be open. That should have told you where to start looking, and at the least told you you should have posted the code that opened the connection as part of your question.
Thanks for everyone. I sloved my problem. This what i cahnge in my code
Dim lngRecCount As Long
lngRecCount = 0
rcdDNE.MoveFirst
With cmdCommand
.ActiveConnection = objConn
.CommandText = "insert into t_DATA_DneFrc (RTN, AccountNbr, FirstName, MiddleName, LastName, Amount) values ('" & rcdDNE("RTN") & "', '" & rcdDNE("AccountNbr") & "', '" & rcdDNE("FirstName") & "', '" & rcdDNE("MiddleName") & "', '" & rcdDNE("LastName") & "', '" & rcdDNE("Amount") & "')"
.CommandType = adCmdText
End With
Set rcddnefrc = New ADODB.Recordset
With rcddnefrc
.ActiveConnection = objConn
.Source = "SELECT * FROM T_DATA_DNEFRC"
.CursorType = adOpenDynamic
.CursorLocation = adUseClient
.LockType = adLockOptimistic
.Open
End With
Do Until rcdDNE.EOF
lngRecCount = lngRecCount + 1
frmDNELoad.lblStatus.Caption = "Adding record " & lngRecCount & " of " & rcdDNE.RecordCount & " to database."
frmDNELoad.Refresh
DoEvents
Call CommitNew
rcdDNE.MoveNext
Loop
frmDNELoad.lblStatus.Caption = "DNE Processing Complete."
frmDNELoad.Refresh

How can I upload a file to an Oracle BLOB field using VB6?

I want to take a file from disk and upload it into an Oracle BLOB field, using VB6. How can I do that?
Answering my own question, for reference:
Public Function SaveFileAsBlob(fullFileName As String, documentDescription As String) As Boolean
'Upload a binary file into the database as a BLOB
'Based on this example: http://www.codeguru.com/forum/printthread.php?t=337027
Dim rstUpload As ADODB.Recordset
Dim pkValue AS Long
On Error GoTo ErrorHandler
Screen.MousePointer = vbHourglass
'Create a new record (but leave document blank- we will update the doc in a moment)
'the where clause ensures *no* result set; we only want the structure
strSQL = "SELECT DOC_NUMBER, DOC_DESC, BLOB_FIELD " & _
" FROM MY_TABLE " & _
" WHERE PRIMARY_KEY = 0"
pkValue = GetNextPKValue
Set rstUpload = New ADODB.Recordset
With rstUpload
.CursorType = adOpenKeyset
.LockType = adLockOptimistic
.Open strSQL, myConn
.AddNew Array("DOC_NUMBER", "DOC_DESC"), _
Array(pkValue, documentDescription)
.Close
End With
'They may have the document open in an external application. Create a copy and work with that copy
Dim tmpFileName As String
tmpFileName = GetTempPath & ExtractFileName(fullFileName)
'if the tmp file exists, delete it
If Len(Dir(tmpFileName)) > 0 Then
Kill tmpFileName
End If
'see this URL for info about this subroutine:
'http://stackoverflow.com/questions/848087/how-can-i-copy-an-open-file-using-vb6
CopyFileEvenIfOpen fullFileName, tmpFileName
'Now that our record is inserted, update it with the file from disk
Set rstUpload = Nothing
Set rstUpload = New ADODB.Recordset
Dim st As ADODB.Stream
rstUpload.Open "SELECT BLOB_FIELD FROM MY_TABLE WHERE PRIMARY_KEY = " & pkValue
, myConn, adOpenDynamic, adLockOptimistic
Set st = New ADODB.Stream
st.Type = adTypeBinary
st.Open
st.LoadFromFile (tmpFileName)
rstUpload.Fields("BLOB_FIELD").Value = st.Read
rstUpload.Update
'Now delete the temp file we created
Kill (tmpFileName)
DocAdd = True
ExitPoint:
On Error Resume Next
rstUpload.Close
st.Close
Set rstUpload = Nothing
Set st = Nothing
Screen.MousePointer = vbDefault
Exit Function
ErrorHandler:
DocAdd = False
Screen.MousePointer = vbDefault
MsgBox "Source: " & Err.Source & vbCrLf & "Number: " & Err.Number & vbCrLf & Err.Description, vbCritical, _
"DocAdd Error"
Resume ExitPoint
End Function

Resources