Combine rights from 2 SQL-users - sql-server-2008

Is it anyhow possible to merge 2 SQL logins, so that I can access 2 databases with different logins at the same server?
I'm using ASP Classic (ADODB) and SQL Server 2008

If you want to use two different sets of credentials you'll need to use two connection objects (or constantly close and reopen one).
Eg:
<%
dim dbA, dbB
Set dbA = server.createobject("adodb.connection")
Set dbB = server.createobject("adodb.connection")
Set rs = server.createobject("adodb.recordset")
dbA.open "ConnectionStringForYourFirstDatabase"
dbB.open "ConnectionStringForYourSecondDatabase"
'#### Execute something to database 1 using connection string 1
set rs = dbA.execute("")
'#### Execute something to database 2 using connection string 2
set rs = dbB.execute("")
'#### Tidy Up
set dbA = nothing
set dbB = nothing
%>

Related

Access with 1 MySQL Table asking for credentials

I have a access database using a local sql server backend for all tables except 1 web based MySQL table. The MySQL table has 50 rows or so, 3 fields, not big at all. I have a odbc connection setup and the table is linked with the password saved. This table is updated 30 times per day at most... Sometimes the connection breaks and the MySQL connection popup will appear... clicking test will result in a success, and clicking ok will allow the code to proceed. It is doing a 1 line update (SET LastUpdatedDate = #" & now() & "# WHERE ItemID = 'xyz').
I want to capture an error, or get it to continue without the connection if it is unavailable... but it appears no error is generated. I would rather not update the table when this happens, then have to physically select ok to get it running again. This problem exists from multiple locations, on multiple PCs around the US. I assume it is the server the MySQL db is hosted on that is having problems - I just want to know how to ignore them and move on with the other code... again, no error generated (So On Error ... won't work). Any Ideas? Using Access 2016.
UPDATE: My current setup is to ping the server... and if the ping gets a response, I assume it is up... then I run 'CurrentDb.Execute "UPDATE XYZ SET ABC = 'DEF' WHERE GHI = 'JKL'". That simple. If I try to query the table XYZ and it isn't available, I get the same connection popup. How should I go about refreshing the table? Delete the link and recreate?
NEW UPDATE
Finally got around to try out the DSN-less pass through query proposed by Andre below. When I get to the 'execute' step I get an error saying I cannot execute a select query... but it is an update query. Here is the SQL string... .SQL = "UPDATE [Status] SET ItemDate = NOW() WHERE PlantID = '" & PlantID & "' AND ItemID = '" & ItemID & "'"
I suggest that instead of running an Access query on the linked table, you use a DSN-less Pass-Through query that you create on the fly.
This should either always work, or raise a trappable error.
Const ConnectString = "ODBC;DRIVER={MySQL ODBC 5.1 Driver};SERVER=your.server.com;PORT=3306;DATABASE=mydatabase;UID=myuserid;PWD=mypassword"
Dim qdf As DAO.QueryDef
Set qdf = CurrentDb.CreateQueryDef("")
With qdf
' Setting .Connect turns it into a Pass-Through query
.Connect = ConnectString
' Need to set this for non-SELECT queries
.ReturnsRecords = False
' Note: you need to use MySql syntax here, not Access SQL, especially the correct date format
.SQL = "UPDATE XYZ SET ABC = 'DEF' WHERE GHI = 'JKL'"
' or since MySql has a NOW() function too, just this:
.SQL = "UPDATE foo SET LastUpdatedDate = NOW() WHERE ItemID = 'xyz'"
.Execute
End With
You can also try a saved Pass-Through query, it might work as well. Then you would only need to supply the current .Sql, not the connect string.
Maybe you will get an helpful error if you execute your SQL command with the option dbFailOnError ? Like CurrentDB.Execute("Your SQL", dbFailOnError)
Before trying the UPDATE, do a simple SELECT. If it does not return a reasonable result, assume that the connection is down.

Classic ASP global.asa SQL Server 2008 connection string

I have been given a web application written in Classic ASP to port from Windows 2003 Server (SQL Server 2000 and IIS 6) to Windows 2008 Server (SQL Server 2008 and IIS 7.5).
The site uses a GLOBAL.ASA file to define global variables, one of which is the connection string (cnn) to connect to SQL Server.
Below is the (old) connection string from GLOBAL.ASA:
Sub Application_OnStart
Dim cnnDem, cnnString
Set cnnDem = Server.CreateObject("ADODB.Connection")
cnnDem.CommandTimeout = 60
cnnDem.Mode = admodeshareexclusive
cnnString = "Provider=SQLOLEDB; Data Source=192.xxx.x.xx; User Id=xxxx; Password=xxxxx; default catalog=xxxxxxx;"
Application("conString")=cnnString
Call cnnDem.Open(cnnString)
Application("cnn") = cnnDem
End Sub
The .ASP pages then use the cnn value like this:
strSQL = "Select * From tblUtilities order by companyname"
Set rs = Server.CreateObject("ADODB.Recordset")
rs.Open strSQL, Application("cnn"), adOpenKeyset
However I could not get the connection string to connect – I whittled it down to a “Failed to Login” error message (no matter what Login ID I tried).
I edited the GLOBAL.ASA file as follows and it works.
Sub Application_OnStart
Dim cnnDem, cnnString
Set cnnDem = Server.CreateObject("ADODB.Connection")
cnnDem.CommandTimeout = 60
cnnString = "Provider=SQLNCLI10.1;User Id=xxxx; Password=xxxxx;Initial Catalog=xxxxxxx;Data Source=xxxxxx\SQLEXPRESS;"
Application("conString")=cnnString
Application("cnn")=cnnString
Call cnnDem.Open(cnnString)
End Sub
The main difference is that cnn now contains the connection string, where as previously cnn was an object referring to ADOBD.Connection.
The question I have is what impact (if any) will this have on the application. I have done some basic (local) testing and everything looks ok at the moment. But I am wondering if there might be multi-user issues (or something of that nature) that might arise when this site is deployed again.
One of the best and easiest way to connect to create a Database Connection String is to crease a new ASP file in the root directory or elsewhere and include the Connection string into it:
//Global.asp //
<%
Dim connectionString
connectionString = "PROVIDER=SQLOLEDB;DATA SOURCE=YourSQLServer;UID=sa;PWD=*******;DATABASE=YourDataBase"
%>
Then create an include statement in each file that you would like to call this connection.
<!-- #include virtual="global.asp" -->
Then, where you need to setup your connection call, simply use your code to connect to the Database:
<%
Set adoCon = Server.CreateObject("ADODB.Connection")
adoCon.Open = ConnectionString
Set rsReports = Server.CreateObject("ADODB.Recordset")
strSQL = "Select * From Customers"
rsReports.Open strSQL, adoCon
%>
I keep the Connection String in Global.asa but create the connection in a separate function loaded as needed. An Application connection object may not be aware of temporary network issues that may close that connection, and then future attempts to use the connection will not be successful.
Hope this makes sense.

Microsoft Access (MySQL back end) queries with parameters

I am trying to convert the back end of an Access database to MySQL. So far, I have no problems converting the tables, and updating the queries with no parameters to pass through queries.
However, I am at a lost at figuring out how to deal with queries with parameters requiring inputs from users.
Anyone could give me some pointers?
If you are inheriting back-end code that sends data to an Access DB there are few things to look out for.
Dates are handled differently in Access to MySQL.
Access requires that you enclose dates in ## like #05/05/2012#. In MySQL, just enclose them in single quotes, '05/05/2012'.
Column and table names that contain spaces are enclosed in squared brackets like [table name] in Access and backsticks like table name in MySQL.
For linked tables, something like:
SELECT ID, AText
FROM LinkedTable
WHERE AText=[Forms]![Form1]![txtText]
Should work quite well. There are limitations, in which case you will need a pass-through, but most queries can be written at the Access end just as if the table was a local MS Access table.
To code a pass-through, you might say:
Dim objconn As Object
Dim cmd As Object
''Late binding
Set objconn = CreateObject("ADODB.Connection")
objconn.Open ServerCon
Set cmd = CreateObject("ADODB.Command")
Set cmd.ActiveConnection = objconn
cmd.CommandText = "InsertUser"
cmd.Parameters.Append _
cmd.CreateParameter("UserName", adVarChar, adParamInput, 50, "param1")

ALTER TABLE Syntax Error

I'm having trouble with an update query in Access.
I'm trying to do two things, add a field to a table, and change all values in another field to the same value.
ALTER TABLE 103 ADD COLUMN test TEXT;
UPDATE 103 SET [103].Workcenter = "103";
When I run these two lines independently, they work fine, but when I put them in the same query I get "Syntax Error in ALTER TABLE" statement. Does anyone know why I can't do this?
It would also be great if I could add a column and update all values in that field to a default value. I've tried DEFAULT in the ALTER TABLE command but it's not working either.
Thanks in advance for suggestions!
AS ron tornambe said, you can't have more than a single command in an Access Query. They do not support batching.
VBA code is your friend when doing alterations on tables: The Data Definition Language used in Access is more limited than what is available from VBA when directly manipulating the database objects.
For instance, to do exactly what you seek:
Public Sub AddFieldAndUpdate()
' Initialise '
Dim db As DAO.Database
Dim tb As DAO.TableDef
Dim fd As DAO.Field
Set db = CurrentDb()
' Get the 103 table '
Set tb = db.TableDefs("103")
' Create a new 'test' field, 128 char long '
Set fd = tb.CreateField("test", dbText, 128)
' Set the Default value for the new field '
fd.DefaultValue = "000"
' Add the new field to the 103 table
tb.Fields.Append fd
' Now do the update
db.Execute "UPDATE 103 SET [103].Workcenter = '103';", dbFailOnError
Debug.Print "Number of Updated records: " & db.RecordsAffected
' Cleanup
Set fd = Nothing
Set tb = Nothing
Set db = Nothing
End Sub
This is the jest of it, although you probably want to do more than that, for instance, set indexes, default formatting, etc as required.
Some table design features are only available when using the DAO object model to modify the TableDef. Others are only available when executing a DDL statement from an ADO connection.
Your table design change involves features which are available with either method. Use whichever you wish, but I would personally choose this way:
Dim strDdl As String
strDdl = "ALTER TABLE 103 ADD COLUMN test TEXT(128) DEFAULT ""000"";"
CurrentProject.Connection.Execute strDdl

sql Query in VBA code

If I want to code the following in VBA how do I do it
QUERY1:
SELECT field1, Min(field4) AS MinField4, Max(field5) AS MaxField5
FROM Table1
GROUP BY field1;
SELECT Query1.field1, Table1.field2, Table1.field3, Query1.MinField4,
Query1.MaxField5
FROM Query1 INNER JOIN Table1 ON (Query1.field1 = Table1.field1) AND
(Query1.MinField4 = Table1.field4) AND
(Query1.MaxField5 = Table1.field5);
I know for executing the SQL I store it as as string and write run SQL.
but how do I code storing query1 as a persistent object that can be referenced in other SQL statements?
Here some code that will fill up a dataset with your results
Dim cnn As ADODB.Connection
Dim recordset As ADODB.Recordset
Dim strSQL As String
Set cnn = CurrentProject.Connection
strSQL = "SELECT blah ..."
recordset.Open strSQL, cnn, adOpenKeyset, adLockOptimistic, adCmdText
'do what you want now.
oh yeah its been a while but you probably want to clean up too
Set recordset = Nothing
'etc..
I take it your question is "How do I create a new query in Microsoft Access using code?"
There are two solutions:
Microsoft Access will accept the DDL statement CREATE VIEW. So you can construct that statement in code and then execute it against the database via OLE DB e.g. ADO in VBA code.
The database object in MS Access contains a collections property called QueryDefs and you can access that to manipulate (and create) queries stored in the database.
you could just create a query and paste that SQL into the SQL View (available from the query design window).