Update - 2/14/21
Ok, this is where I'm at now. the code below works! Yay! However, there are no records in the database to read.
''''
<%
db_server = "my_server"
db_name = "my_db-name"
db_username = "my_username"
db_userpassword = "my_password"
db_fieldname = "my_fieldname"
db_tablename = "my_tablename"
db_schema = "my_schema"
'Establish a connection to the database
Set conn = Server.CreateObject("ADODB.Connection")
conn.Open("Provider=SQLOLEDB; Data Source=" & db_server & "; Inital catalog=" & db_name & "; User ID=" & db_username & "; password=" & db_userpassword & ";")
'Test the connection to make sure it is available and it's open.
If IsObject(conn) then
response.write "The connection is active!<br />"
if conn.State = 1 then
response.write "A connection is made, and is open.<br />"
end if
end if
'Query the tables I need
Set rs= conn.execute("SELECT * FROM [" & db_name & "].[" & db_schema & "].[" & db_tablename & "]")
do until rs.EOF
count = count + 1
for each x in rs.Fields
Response.Write(x.name)
Response.Write(" = ")
Response.Write(x.value & "<br>")
next
Response.Write("<br>")
rs.MoveNext
loop
Set conn = nothing
response.write "Records found = " & count
%>
''''
So with the part above is actually working again. I set out to add a record to the database with the code below. It seems to work as it does not cause an error. However, it is not adding the record though.
''''
<%
db_server = "my_server"
db_name = "my_db-name"
db_username = "my_username"
db_userpassword = "my_password"
db_fieldname = "my_fieldname"
db_tablename = "my_tablename"
db_schema = "my_schema"
count = 0
'Establish a connection to the database
Set conn = Server.CreateObject("ADODB.Connection")
conn.Open("Provider=SQLOLEDB; Data Source=" & db_server & "; Inital catalog=" & db_name & "; User ID=" & db_username & "; password=" & db_userpassword & ";")
'Test the connection to make sure it is available and it's open.
If IsObject(conn) then
response.write "The connection is active!<br />"
if conn.State = 1 then
response.write "A connection is made, and is open.<br />"
end if
end if
sql="INSERT INTO " & db_name & "." & db_schema & "." & db_tablename & " (fname,lname,email,upassword)"
sql=sql & " VALUES "
sql=sql & "('John',"
sql=sql & "'Doe',"
sql=sql & "'JohnD#email.com',"
sql=sql & "'12345')"
on error resume next
conn.Execute sql,recaffected
if err<>0 then
Response.Write("No update permissions!")
else
Response.Write("<h3>" & recaffected & " record added</h3>")
end if
conn.close
Set conn = nothing
%>
''''
This is where I have been stuck. It is not writing to the database. It just runs and nothing gets done. If I remove the resume next portion, it still works with no error but, still, no record being written cause the resume next. I have tried two different users to run the code. Both of which have read and write permission. Now what? I'll just keep trying until someone puts me out of my misery... lol!
Well, it seems a friend and I finally found out what was going on. The code actually works but, for some reason, the database's ID field is not auto-incrementing. So, in order to add a record, we had to first check to see how many records are in the DB then add 1 to the count to use for our new records id. Seems every solution leads to a new issue. That's programing...
Just in case any of that makes sense or even if it doesn't make sense, here the id's properties.
ID (PK, uniqueidentifier, not null)
db_server = "my_server"
db_name = "my_db-name"
db_username = "my_username"
db_userpassword = "my_password"
db_fieldname = "my_fieldname"
db_tablename = "my_tablename"
db_schema = "my_schema"
count = 0
'Establish a connection to the database
Set conn = Server.CreateObject("ADODB.Connection")
conn.Open("Provider=SQLOLEDB; Data Source=" & db_server & "; Inital
catalog=" & db_name & "; intergaraded security = false ; User ID=" &
db_username & "; password=" & db_userpassword & ";")
'Test the connection to make sure it is available and it's open.
'If IsObject(conn) then
' response.write "The connection is active!<br />"
' if conn.State = 1 then
' response.write "A connection is made, and is open.<br />"
' end if
'end if
Set rs= conn.execute("Select top 1 id from " & db_name & "." & db_schema & "." & db_tablename & " order by id desc")
on error resume next
do until rs.EOF
for each x in rs.Fields
count = x.value
'response.write x.value & "<br>"
next
rs.MoveNext
loop
'conn.Execute sql,recaffected
if err<>0 then
Response.Write("<br>id: " & err.description)
else
'Response.Write("<h3>" & count & " record in db</h3>")
end if
'conn.close
Set rs= conn.execute("Select top 1 id from " & db_name & "." & db_schema & "." & db_tablename & " order by id desc")
sql=sql & " VALUES "
sql=sql & "(" & cstr(count + 1) & ","
sql=sql & "'John',"
sql=sql & "'Doe',"
sql=sql & "'user#website.com',"
sql=sql & "'1234abcd')"
'response.write sql & "<br>"
on error resume next
conn.Execute sql,recaffected
if err<>0 then
Response.Write("<br>insert: " & err.description)
else
'Response.Write("<br>" & recaffected & " record added</h3>")
end if
conn.close
Set conn = nothing
I left all the error checking in there but, it is all commented out. I hope this is the last time I have to come back to this. Goodluck!
Related
I have this VBA code in MS Access (Connect, Exec and Disconnect are my own ADO subs/functions):
Private Sub cmdShipOrder_Click()
Dim intShipmentID As Integer
Dim rsShipment, rsShipmentDetail As Recordset
On Error GoTo ErrHandler
If Me.ReservationStatus <> "ZBOŽÍ KOMPLETNĚ REZERVOVÁNO" Then
MsgBox "Nejprve je nutné do objednávky rezervovat hmotné zboží.", vbCritical + vbOKOnly, "Chyba"
Exit Sub
End If
If MsgBox("Bude vytvořena expedice a celá objednávka bude označena jako expedovaná. Pokračovat?", vbExclamation + vbYesNoCancel, "Upozornění") <> vbYes Then Exit Sub
Connect
Exec "INSERT INTO tbl1Shipments (CustomerID, ShippingMethodID, ShipToID, CarrierID, ShipmentCode, DateShipped) " & _
"VALUES (" & Me.CustomerID & ", " & _
Me.ShippingMethodID & ", " & _
Me.ShipToID & ", " & _
Me.CarrierID & ", " & _
"'" & Year(Date) & "EXP" & Format(DCount("*", "dbo_tbl1Shipments", "ShipmentCode LIKE '%" & Year(Date) & "EXP%'") + 1, "000") & "', " & _
"GETDATE())"
intShipmentID = DMax("ShipmentID", "dbo_tbl1Shipments", "CustomerID=" & Me.CustomerID)
Conn.BeginTrans
Set rsShipment = CurrentDb.OpenRecordset("SELECT * FROM dbo_v_SalesOrderSub WHERE SalesOrderID=" & Me.SalesOrderID)
rsShipment.MoveFirst
Do Until rsShipment.BOF Or rsShipment.EOF
Exec "INSERT INTO tbl1ShipmentDetails (ShipmentID, SalesOrderDetailID, Quantity) " & _
"VALUES (" & intShipmentID & ", " & _
rsShipment("SalesOrderDetailID") & ", " & _
rsShipment("Quantity") & ")"
rsShipment.MoveNext
Loop
Set rsShipmentDetail = CurrentDb.OpenRecordset("SELECT * FROM dbo_v_ShipmentSub WHERE ShipmentID=" & intShipmentID)
rsShipmentDetail.MoveFirst
Do Until rsShipmentDetail.BOF Or rsShipmentDetail.EOF
If rsShipmentDetail("ProductTypeID") <> 3 Then
Exec "UPDATE tbl1Units " & _
"SET ShipmentDetailID=" & rsShipmentDetail("ShipmentDetailID") & " " & _
"WHERE SalesOrderDetailID=" & rsShipmentDetail("SalesOrderDetailID")
End If
rsShipmentDetail.MoveNext
Loop
Conn.CommitTrans
rsShipment.Close
Set rsShipment = Nothing
rsShipmentDetail.Close
Set rsShipmentDetail = Nothing
Disconnect
Exit Sub
ErrHandler:
MsgBox "CHYBA: " & Err.Description
Conn.RollbackTrans
Exec "DELETE FROM tbl1Shipments WHERE ShipmentID=" & intShipmentID
If Not rsShipment Is Nothing Then
rsShipment.Close
Set rsShipment = Nothing
End If
If Not rsShipmentDetail Is Nothing Then
rsShipmentDetail.Close
Set rsShipmentDetail = Nothing
End If
Disconnect
When I run this without Conn.BeginTrans and Conn.CommitTrans, the code works just fine. However when I leave the transaction commands there, I get a "query timeout" error from SQL Server. Specifically on a second cycle in the INSERT INTO tbl1ShipmentDetails statement. Why?
I am opening an SQL Server Connection in EXCEL VBA and on the objMyCmd.Execute line when it is using the SQL script I am getting this error message:
"Run-time error '-2147217900 (80040e14)') Automation error"
I have reviewed other SO posts that seem to reference an issue with the connection string itself, but I don't believe that is the issue as I am able to pull the first few variables listed when eliminating the rest of the SQL script.
I have attempted to review the SQL code to see if I am using an incorrect format, or if the language is not written properly and I am not able to determine the issue. I am hoping with some Q & A we may notice something I have missed in how this is written? Please let me know if there is additional information I can provide, below is the code up to the point of error.
Sub SQL_GetAgentChart()
Dim dtDate As Date
Dim myTable As ListObject
Dim DataServer As String
Dim Database As String
Dim constring As String
DataServer = "GLSSQLMADP2"
Database = "PERF_MGMT_BWRSRV_PROD"
constring = "Driver={SQL Server};Server=" & DataServer & "; Database=" & Database & "; Trusted_Connection=yes"
Dim AVStartDate As Date
Dim AVEndDate As Date
Dim RepID As Long
'Declare variables'
Set objMyConn = New ADODB.Connection
Set objMyCmd = New ADODB.Command
Set objMyRecordset = New ADODB.Recordset
Set myTable = Worksheets("Witness").ListObjects("tblWitness")
AVStartDate = DateValue("Mar 01, 2016")
AVEndDate = DateValue("Mar 31, 2016")
RepID = 2040
'Open Connection'
objMyConn.ConnectionString = constring
objMyConn.Open
'Set and Excecute SQL Command'
Set objMyCmd.ActiveConnection = objMyConn
objMyCmd.CommandText = " " & _
"SELECT PERSN_XTRNL_ID_NR, SOURCE, LOGGINGTS, DD7, CUREREASON, CUREDATE, LNSTATUS " & _
"FROM TTB " & _
"WITH INCALL AS (SELECT T.CUREREASON, CUREVALUE " & _
"FROM TTB T " & _
"JOIN PERSONNEL P ON T.PERSONNELID = P.PERSONNELID " & _
"LEFT JOIN CURETRANSLATE C ON T.CUREREASON = C.CUREREASON AND T.LNSTATUS = C.STATUS " & _
"WHERE T.PERSONNELID = " & RepID & " " & _
"AND LOGGINGTS > '" & AVStartDate & "' " & _
"AND LOGGINGTS < '" & AVEndDate + 1 & "' " & _
"AND INCOMING = 1 " & _
"AND DD7 > 0), OUTCALL AS (SELECT T.CUREREASON, CUREVALUE " & _
"FROM TTB T " & _
"JOIN AVAYA A ON T.UID = A.TTBUID " & _
"LEFT JOIN CURETRANSLATE C ON T.CUREREASON = C.CUREREASON AND T.LNSTATUS = C.STATUS " & _
"WHERE PERSONNELID = " & RepID & " " & _
"AND LOGGINGTS > '" & AVStartDate & "' " & _
"AND LOGGINGTS < '" & AVEndDate + 1 & "' " & _
"AND INCOMING = 0 " & _
"AND A.AVAYAGROUP IN ('15', '1A', '1B', '1C', '1D', '1E', '1F', '1G', '1H') " & _
"AND DD7 > 0) "
objMyCmd.CommandType = adCmdText
objMyCmd.Execute
I have a table in MS Access 2003 in which I want to archive all old data.
The criteria is that the creation data should be less than a specific date.
I can write a SQL statement to select them, but I don't know how to move them to another database/table? Assuming that the archive database/table is already created and data structure matches current table.
Also how I can make sure that all data which is moved to archive table is removed from current table?
I want to write VBA code to run the command check that data is archived correctly.
You want to 1) move data meeting certain criteria from one table to another, existing table with the same format. 2) You want to "make sure that all data which is moved to archive table is removed from current table." And 3) you "want to write VBA code to run the command check that data is archived correctly."
Contrary to popular opinion, Access does support transactions (the claim that Access SQL does not support transactions is true, but we can still use transactions in VBA code). So modifying code in this post to use transactions in a workspace, I believe this would do the trick (tested in Access 2010 using DAO).
The code to lock, get counts and unlock is not really necessary, and may increase the difficulty of implementing the archive, since it will require that no one be writing to the table while you're updating it. And if it did find a problem, Access does not support transaction logging, so you would have a very short list of options as to how to fix it. But it sounded like you wanted to be absolutely sure the counts were correct, so this adds another level, arguably unnecessary, of checking.
Option Compare Database
Option Explicit
Sub ArchiveOldRecords()
Dim nSourceCount As Long, nMoveCount As Long, nDestCount As Long
Dim strSQL As String, sMsg As String
Dim rsLock As DAO.Recordset
Dim rsBefore As DAO.Recordset, rsAfter As DAO.Recordset
Dim wrk As Workspace, db As DAO.Database
Const strcTableSource As String = "t_TestWithDate" ' Move records FROM table
Const strcTableArch As String = "t_ArchiveTestWithDate" ' Move records TO table
Const strcWHERE As String = " WHERE field2 < " _
& "DATEADD(""yyyy"", -1, Date())" ' Select date field and DATEADD params
Const strcCount As String = "SELECT COUNT(*) As "
On Error GoTo TrapError
Set db = CurrentDb
Set wrk = DBEngine.Workspaces(0)
' Lock table - so no one can add/delete records until count is verified
Set rsLock = db.OpenRecordset(strcTableSource, dbOpenTable, dbDenyWrite)
' Get initial table counts
Set rsBefore = db.OpenRecordset( _
strcCount & "SourceCount, " _
& "(SELECT COUNT(*) FROM " & strcTableSource _
& strcWHERE & ") As MoveCount, " _
& "(SELECT COUNT(*) FROM " & strcTableArch & ") As DestCount " _
& "FROM " & strcTableSource & ";", dbOpenForwardOnly)
nSourceCount = rsBefore!SourceCount
nMoveCount = rsBefore!MoveCount
nDestCount = rsBefore!DestCount
rsBefore.Close
wrk.BeginTrans
' Copy records
strSQL = "INSERT INTO " & strcTableArch _
& " SELECT * FROM " & strcTableSource & " " & strcWHERE & ";"
db.Execute strSQL, dbFailOnError
' Unlock table - only needed for counts
rsLock.Close
Set rsLock = Nothing
' Delete copied records
strSQL = "DELETE * FROM " & strcTableSource & " " & strcWHERE & ";"
db.Execute strSQL, dbDenyWrite + dbFailOnError
' Lock table - only needed for counts
Set rsLock = db.OpenRecordset(strcTableSource, dbOpenTable, dbDenyWrite)
wrk.CommitTrans
' Get final table counts
Set rsAfter = db.OpenRecordset( _
strcCount & "SourceCount, " _
& "(SELECT COUNT(*) FROM " & strcTableSource _
& strcWHERE & ") As MoveCount, " _
& "(SELECT COUNT(*) FROM " & strcTableArch & ") As DestCount " _
& "FROM " & strcTableSource & ";", dbOpenForwardOnly)
' Double-check counts
If (rsAfter!SourceCount <> nSourceCount - nMoveCount) _
Or (rsAfter!DestCount <> nDestCount + nMoveCount) _
Or (rsAfter!MoveCount > 0) Then
sMsg = vbNewLine
sMsg = sMsg & "Records in " & strcTableSource & " before: "
sMsg = sMsg & nSourceCount
sMsg = sMsg & vbTab & "after: "
sMsg = sMsg & rsAfter!SourceCount
sMsg = sMsg & vbNewLine
sMsg = sMsg & "Records to archive from " & strcTableSource & ": "
sMsg = sMsg & nMoveCount
sMsg = sMsg & vbTab & "after: "
sMsg = sMsg & rsAfter!MoveCount
sMsg = sMsg & vbNewLine
sMsg = sMsg & "Records in " & strcTableArch & " before: "
sMsg = sMsg & nDestCount
sMsg = sMsg & vbTab & "after: "
sMsg = sMsg & rsAfter!DestCount
MsgBox "Count double-check failed" & sMsg
End If
Exit_Sub:
On Error Resume Next
' Unlock table and close recordsets
rsLock.Close
rsBefore.Close
rsAfter.Close
Set rsBefore = Nothing
Set rsAfter = Nothing
Set rsLock = Nothing
Set db = Nothing
Set wrk = Nothing
Exit Sub
TrapError:
MsgBox "Failed: " & Err.Description
wrk.Rollback
Err.Clear
Resume Exit_Sub
End Sub
There is no MOVE command but you can copy the records across to the target and then use a similar query to remove them from the source when you are sure you have no Paste Errors.
INSERT INTO MyArchive (fld1, fld2, fld3, fld4) SELECT fld1, fld2, fld3, fld4 FROM MyTable WHERE fld4 < DATEADD("y", -5, Date())
That copies across everything older than 5 years. After confirming the transfer,
DELETE * FROM MyTable WHERE fld4 < DATEADD("y", -5, Date())
That's off the top of my head and I transition between T-SQL and MS Access a fair bit but I think that is pretty solid Access query code. Your own field lists will vary accordingly.
I have a database with a table called LaptopTrolleyWU that has the following structure:
ComputerName varchar(50)
TimeStamp datetime
Log varchar(MAX)
I am trying to insert text into the Log field from a VBScript script, but cannot work out the syntax in order to do so.
This is what I have so far:
For I = 0 to updatesToInstall.Count - 1
WScript.Echo I + 1 & "> " & _
updatesToInstall.Item(i).Title & _
": " & installationResult.GetUpdateResult(i).ResultCode
objFile.WriteLine(I + 1 & "> " & updatesToInstall.Item(i).Title & ": " & installationResult.GetUpdateResult(i).ResultCode)
Connection.Execute "INSERT INTO LaptopTrolleyWU (Log) VALUES ('" & I + 1 & "'> '" & updatesToInstall.Item(i).Title & "': '" & installationResult.GetUpdateResult(i).ResultCode & "')"
Next
End If
I get an error that reads
'Microsoft OLE DB Provider for ODBC Drivers: [Microsoft][ODBC SQL
Server Driver][SQL Server][Incorrect syntax near ')'.
What am I doing wrong?
If it helps, this is how I originally connect to the DB, which I might have done incorrectly...
Set Connection = CreateObject("ADODB.Connection")
Set Recordset = CreateObject("ADODB.Recordset")
Dim ConnectionString
ConnectionString = "Driver={SQL Server};Server=server;Trusted_Connection=no;Database=LaptopTrolly;Uid=Laptop;Pwd=password"
Connection.Open ConnectionString
This is what I did in the end:
strLogText = I + 1 & "> " & updatesToInstall.Item(i).Title & ": " & installationResult.GetUpdateResult(i).ResultCode
strSQLCmd = "INSERT INTO dbo.LaptopTrolleyWU (ComputerName,TimeStamp,Log) VALUES ('" + strComputerName + "', '" + dtTimeStamp + "' , '" + strLogText + "')"
Connection.Execute strSQLCmd
Your task is to write the value of a string expression into a log file and a database field (I assume the .Echo is just for debugging). Then you should invest into a variable to hold the value of the expression and use that twice:
v = I + 1 & "> " & updatesToInstall.Item(i).Title & ": " & installationResult.GetUpdateResult(i).ResultCode
Writing to a file is easy, because you just need the plain data:
objFile.WriteLine v
(no spurious param list ()!). You need an INSERT statement to put v into the database; the value of v has to be single quoted:
>> v = "pipapo"
>> s = Replace("INSERT INTO LaptopTrolleyWU (Log) VALUES ('#v')", "#v", v)
>> WScript.Echo s
>>
INSERT INTO LaptopTrolleyWU (Log) VALUES ('pipapo')
>>
If you then do
WScript.Echo s
Connection.Execute s
you can be sure that the statement you execute is the code you have visually inspected.
Your expressions differ:
I + 1 & "> " & updatesToInstall.Item(i).Title & ": " & installationResult.GetUpdateResult(i).ResultCode
I + 1 & "'> '" & updatesToInstall.Item(i).Title & "': '" & installationResult.GetUpdateResult(i).ResultCode
The extra single quotes in the INSERT statement make the SQL parser assume you want to compare string literals.
Hey all i am trying to get a connection to my SQL server version 10.50.2500 in Classic ASP
My code in the .asp page is (including all connection strings I've tried using):
Set objConn = Server.CreateObject("ADODB.Connection")
Set objRS = Server.CreateObject("ADODB.Recordset")
'objConn.ConnectionString = "Provider={SQL Server};Server=xxx.xxx.xxx.xxx\SQLEXPRESS;Database=JForm;User ID=xxxx;Pwd=xxxx"
'objConn.ConnectionString = "Driver={SQL Server};Server=xxx.xxx.xxx.xxx\SQLEXPRESS;Database=JForm;Uid=xxxx;Pwd=xxxx;"
'objConn.ConnectionString = "Provider=SQLNCLI10;Server=xxx.xxx.xxx.xxx,1433;Database=JForm;Uid=xxxx;Pwd=xxxx;Persist Security Info=True"
'objConn.ConnectionString = "Provider=SQLNCLI;Server=.\SQLEXPRESS;Database=JForm;Uid=xxxx;Pwd=xxxx"
objConn.ConnectionString = "Driver={SQL Server Native Client 10.0};Server=xxx.xxx.xxx.xxx\SQLEXPRESS;Database=JForm;Uid=xxxx;Pwd=xxxx"
strSQL = "UPDATE jURLS " & _
"SET rssFeedURL = 'http://www.xxxx.com/rss/" & rss & "'," & _
"csvURL = 'http://www.xxxx.com/csv/" & csv & "'," & _
"jFormName = '" & forname & "'," & _
"isActive = " & active & " " & _
"WHERE jFormName = '" & forname & "'"
objConn.open
objRS.Open strSQL, objConn, 1,3
'If Not objRS.EOF Then
'iterate through records here
'Else
'no records found
'End If
objRS.close
Set objRS=Nothing
objConn.close
Set objConn=Nothing
It seems to crash on the objConn.open. However, it only gives me a 500 - Internal server error. and not an error thats helpful!
Once i take the database code from the page and leave everything else, it works without the 500 - Internal server error being displayed.
What else can i try in order to get this to work?
you have an extra comma here :
"isActive = " & active & "," & _
change it to:
"isActive = " & active & " " & _
about the connection error, try debugging using the connection.errors collection
On Error Resume Next
objConn.open
for each errobj in objConn.Errors
Response.write errobj.Number & "<br />"
Response.write errobj.Description & "<br />"
next
On Error Goto 0
Try:
response.write(strSQL) <-- this will allow you to look at your current SQL statement and see if it makes sense.
set objRS = objConn.execute(strSQL)