how to access sql server from asp page - sql

We have a legacy, homegrown timesheet system (ASP, microsoft sql server 2005) that I need to clone to another computer for backup purposes. (I know very little about this stuff, so pleas be gentle)
I've got most of the pieces in place (IIS, Sql Server, table import / creation). But, the ASP page to access the timesheet pages is choking on access to the sql server.
here is the line it's crashing on: conn.open Session("sConnStr")
This is the connection string;
sConnStr = "Server=MYSERVER-D01;DATABASE=MYDATABASE;UID=MyDatabaseUser;PWD=MyDatabaseUser;QuotedID=No;DRIVER={SQL Server};Provider=MSDASQL"
This is the error:
Error Type: Microsoft OLE DB Provider for ODBC Drivers (0x80004005) [Microsoft][ODBC Driver Manager] Data source name not found and no default driver specified /mydir/mypage.asp, line 17 <== shown above
Note that am able to access the db on SQL Server with Windows specified as the authentication using Server Management Studio. However, when i try using SQL Authentication, I get the message "The user is not associated with a trusted SQL connection".
Questions:
How do you set up the user / password on SQL Server 2005?
What is the default driver, and do i need to get it/set it up?
When it talks about the data source name ( see "MYDATABASE" in the
above mentioned connection string), is it talking about one of the
entries you see under "Databases" on the management studio object
explorer?
Thanks for you responses! So far, no luck. I've managed to access the database via management studio object explorer, by doing this;
Enable SQL Authentication:
....Solution
To resolve this issue, follow the instructions to set User Authentication.
SQL Server 2000:
Go to Start > Programs > Microsoft SQL Server > Enterprise Manager
Right-click the Server name, select Properties > Security
Under Authentication, select SQL Server and Windows
The server must be stopped and re-started before this will take effect
SQL Server 2005:
Go to Start > Programs > Microsoft SQL Server 2005 > SQL Server Management Studio
Right-click the Server name, select Properties > Security
Under Server Authentication, select SQL Server and Windows Authentication Mode
The server must be stopped and re-started before this will take effect..."
And
this;
Change the owner to the one being used to access the db
Microsoft SQL Server Management Studio
Right click the DB, change the owner
But I'm still getting exactly the same error message!

To create a new user and assign it to a database you'll need to do the following,
In SQL Server Management Studio, open Object Explorer and expand the
folder of the server instance in which
to create the new login.
Right-click the Security folder, point to New, and then click Login.
On the General page, enter a name for the new login in the Login name
box.
Select SQL Server Authentication. Windows Authentication is the more
secure option.
Enter a password for the login.
Select the password policy options that should be applied to the new
login. In general, enforcing password
policy is the more secure option.
Click OK.
You will then want to assign that login to a database by creating a new database user,
In SQL Server Management Studio, open Object Explorer and expand the
Databases folder.
Expand the database in which to create the new database user.
Right-click the Security folder, point to New, and then click User.
On the General page, enter a name for the new user in the User name box.
In the Login name box, enter the name of a SQL Server login to map to
the database user.
Click OK.
You'll want to make that user the db_owner. Run the following against your database.
sp_addrolemember #rolename = 'db_owner', #membername = 'usernamehere'
Then use the following connection string format to connect to the database.
Data Source=ServerAddress;Initial Catalog=DatabaseName;User Id=UserName;Password=UserPassword;

If you have a trusted connection from the login that IIS is using the the machine that has SQL Server running on it I would avoid using Username / Password and declare that the connection is trusted in your connection string:
sConnStr = "Server=MYSERVER-D01;DATABASE=MYDATABASE;UID=MyDatabaseUser;PWD=MyDatabaseUser;QuotedID=No;DRIVER={SQL Server};Provider=MSDASQL;Integrated Security=SSPI"
This is to illustrate the change, but in practice you may need to vary the connections string a bit more than that, have a look at http://www.connectionstrings.com/sql-server-2005 for examples.
When it talks about the data source name ( see "MYDATABASE" in the above mentioned connection string), is it talking about one of the entries you see under "Databases" on the management studio object explorer
Yes, your entry for "MYDATABASE" should be the exact name of the database that you see under "Databases". Make sure that you have the "Server" correct too.

Microsoft OLE DB Provider for ODBC Drivers error '80004005'
[Microsoft][ODBC Driver Manager]Data source name not found and no default driver specified.
This usually happens in one of the following scenarios:
* you referenced your connection incorrectly (e.g. spelled the DSN name, or one of the DSN-less string components wrong);
* you referenced a DSN that doesn't exist;
* the user connecting to the DSN or DSN-less connection doesn't have access to the information stored in the registry (see KB #306345);
* you used an English or localized driver detail for your connection string when your system is not set up in that language (see KB #174655); or,
* you are missing the connection string entirely (this can happen if you maintain your connection string in a session variable, and your sessions aren't working; see Article #2157).
Here is the link to the above article (note it is extremely detailed).
link
To answer the last question, MYDATABASE is calling a database by name. If you use 'MYDATABASE' in your string, you will need a database named 'MYDATABASE' in SQL Server.

This connection string should work fine with ASP if this is a SQL server. Replace your values before using obviously.
sConnStr = "provider=SQLOLEDB;Data Source=YourServerName;Initial Catalog=YourDBName;UID=YourUserName;PWD=YourUserPWD;"

The easiest way I have found to deal with these issue is to create a udl file. On your desktop create a new text file and rename it filename.udl. Double click the udl file. Click the Provider Tab > select Microsoft OLE DB Provider for SQL Server > Next. Using the connection tab you should be able to connect to your database. Once test connection succeeds click ok. You can now open the file in a text editor and copy and paste the line that start Provider... to your asp file. You should end up with sConnStr = "Provider..textfromUDLfile"
MSDN - Creating and Configuring Universal Data Link (.udl) Files

I suggest that you create a DAL (Data Access Layer) that can do all the connection stuff for you. Just passit your command an dit can open and close your conenctions and such. In any app you wan tto abstract these different layers as much as posible and that means that your aspx page should call to an object when has the methods that hten get handled by the dal and make the database calls.
Here is the format for connection to the DB. You can put the connecitn string in the web.config file or even do it in code using hte connectionstringbuilder.
you also need to make sure that your project includes the system.data.sqlclient library otherwise this won't work.
The entry in the web config file looks something like this.
<add name="ConString" connectionString="Data Source=localhost;Integrated Security=True;Initial Catalog="DBtouse";Persist Security Info=True;" providerName="System.Data.SqlClient"/>
or
<add key="ConString" value="Server=localhost;user=username;password=password;Initial Catalog=MyDBtouse;pooling=false"/>
the code behind loks like this:
Dim MyConnection As Data.SqlClient.SqlConnection
Dim Constring As New SqlClient.SqlConnectionStringBuilder
Constring.ConnectionString = System.Configuration.ConfigurationSettings.AppSettings("ConString")
Constring.ConnectTimeout = 30
MyConnection.ConnectionString = Constring.ConnectionString
MyConnection.Open()
'Execute code here
MyConnection.Close()
MyConnection = Nothing

Related

SQL Server & RStudio - SQL Connection Almost Working

I've been running into an issue in R Studio with a SQL connection.
We've had an on-prem SQL Server that's been upgraded over the years, and a colleague that set it up no longer is with the organization.
We also have an Azure Server that's loaded with a SQL Server as well that was much more recently set up before they departed.
We have a GUI program we're currently developing, and one of the early steps is a SQL Login connection for the user where the variable is declared (db_user) and changes with their login and passes the password correctly within system variables defined in .Renviron as posted on RStudio's site for references.
Our initial connection string looks like this, and this is the line of code that starts the connection and where I believe the issue may lie first:
db_conn_onprem <- DBI::dbConnect(odbc::odbc(),
Driver = "SQL Server",
Server = Sys.getenv("server"),
Database = Sys.getenv("database"),
UID = Sys.getenv("db_user"),
PWD = Sys.getenv("PWD")
Whenever the Azure connection succeeds, it connects as dbo#Azure\Azure vs On-Prem's guest#Server\Server.
(I can't post in-line screenshots yet)
On-Prem Connection Screenshot: https://i.ibb.co/PmbGt5y/RStudio-SQL.png
Azure Connection Screenshot: https://i.ibb.co/WFY3FqZ/azure1.png
I feel this is something dbo-related since that's where the connection drops.
(variable names anonymized)
Now for the issue:
Whenever we attempt to run a series of queries, our on-prem errors out with this:
Error: nanodbc/nanodbc.cpp:1655: 42000: [Microsoft][SQL Server][SQL Server]Cannot execute as the server principal because the principal "db_user" does not exist, this type of principal cannot be impersonated, or you do not have permission.
<SQL> 'EXECUTE AS LOGIN = 'db_user' SELECT name FROM master.sys.sysdatabases WHERE dbid > 4 AND HAS_DBACCESS(name) = 1 ORDER BY name ASC'
However, run the exact same procedure on the SQL Server in Azure with relatively no major configuration, and it succeeds.
Here's the SQL Code we run:
EXECUTE AS LOGIN = 'db_user' SELECT name
FROM master.sys.sysdatabases
WHERE dbid > 4
AND HAS_DBACCESS(name) = 1
ORDER BY name ASC
I feel like I've exhausted my resources for this, first I thought it was the initial R code or possibly SQL Drivers, however I don't believe that to be the issue since the SQL driver pulls a list of names in R Studio in the Connections context menu, but bounces back the error when attempting to complete the query.
Whenever I'm searching errors for references for this error, I see
Cannot execute as the server principal because the principal "dbo" does not exist, this type of principal cannot be impersonated, or you do not have permission.
Listed as the most commonly related error for the one I'm experiencing, however I've tried a number of those (From blank DB ownerships to unrelated solutions), but I've mostly hit a wall here.
Any assistance would be greatly appreciated.
I feel this is something dbo-related since that's where the connection drops, but I have no clue where to continue going on this issue.
Yep.
This
EXECUTE AS LOGIN = 'db_user'
requires impersonate permission for the login. Which the error message is clearly telling you. It's unclear why you want to impersonate that login instead of simply connecting as the login to begin with.

Connecting to integrated SQL Server in Visual Studio 2016

I'm trying to use OLE DB to connect to the SQL Server that shipped with VS2015 (this should be SQL Server Express I think). Actually I have problems getting my connection string set up. All my attempts resulted in a generic error message.
The errors occurred with this line of code afterwards:
oCon = New OleDbConnection(cConnectstring)
I tried following connection strings:
Server=localhost;Database=main_Table;Trusted_Connection=True;
As well as:
Provider=SQLNCLI11;Data Source=(localdb)\MSSQLLocalDB;DataTypeCompatibility=80;Initial Catalog=main_Table;Integrated Security=True;Connect Timeout=30;Encrypt=False;TrustServerCertificate=True;ApplicationIntent=ReadWrite;MultiSubnetFailover=False
Or:
Provider = sqloledb;Data Source=(localdb)\MSSQLLocalDB; Initial Catalog = main_Table;Integrated Security=SSPI;
where main_Table is the table I try to start with. I used the connection string that I get via right click on that table in the DB explorer as well (that worked for my Access DBs flawlessly).
Does anybody know how to make this work with Ole DB and SQL Server 2016?
Thanks.

Import Excel 2010 to Sql Server 2008

I am using Excel 2010 and sql server 2008 to import the data from excel to sql server. But am unsuccessful. Can you please check the way i am doing ?
sp_CONFIGURE 'show advanced options',1
RECONFIGURE
GO
sp_CONFIGURE 'optimize for ad hoc workloads',1
RECONFIGURE
GO
sp_configure 'Ad Hoc Distributed Queries', 1
GO
RECONFIGURE
SELECT * FROM OPENROWSET('Microsoft.ACE.OLEDB.12.0','Excel 12.0;Database=C:\Users\anayak\AppData\Roaming\Microsoft\Templates\Book1.xlsx; HDR=YES;IMEX=1','SELECT * FROM [sheet1$]');
where i am getting this error
OLE DB provider "Microsoft.ACE.OLEDB.12.0" for linked server "(null)" returned message "Unspecified error".
Msg 7303, Level 16, State 1, Line 1
Cannot initialize the data source object of OLE DB provider "Microsoft.ACE.OLEDB.12.0" for linked server "(null)".
I installed the Microsoft Access Database Engine 2010 Redistributable for Microsoft.ACE.OLEDB.12.0.
But when i use the command "ODBCAD32.EXE" to check the version of my excel then i am getting 14.00.4760.1000.
Then i tried my connection string to -
SELECT * FROM OPENROWSET('Microsoft.ACE.OLEDB.14.0','Excel 14.0;Database=C:\Users\anayak\AppData\Roaming\Microsoft\Templates\Book1.xlsx; HDR=YES;IMEX=1','SELECT * FROM [sheet1$]');
but again it didnt work.
Can you please suggest what i am doing wrong here ?
Thanks.
Re: 7303 error
Distributed Queries in SQL Server, data from XLS
So your main error is likely this;
OLE DB provider "MICROSOFT.JET.OLEDB.4.0" for linked server "(null)" returned message "Unspecified error".
Msg 7303, Level 16, State 1, Line 1
Cannot initialize the data source object of OLE DB provider "MICROSOFT.JET.OLEDB.4.0" for linked server "(null)".
I would check some permissions.
Check the permissions on the Temp folder
This is needed because the provider uses the temp folder while retrieving the data. The folder can be one of the below based on whether you use a local system account or network domain account.
For network accounts, folder is
\Windows\ServiceProfiles\NetworkService\AppData\Local\Temp
and for local system account its \Windows\ServiceProfiles\LocalService\AppData\Local\Temp
Right click on this folder and give it read write access to the account (or group) executing the code. That solved the error for me.
Also
http://blogs.msdn.com/b/spike/archive/2008/07/23/ole-db-provider-microsoft-jet-oledb-4-0-for-linked-server-null-returned-message-unspecified-error.aspx
This is because the SQL Server Service is trying to write the temp DSN to the temp folder for the login that started the service, in this case the Admin/Admin login.
The temp folder is something like: C:\Documents and Settings\Admin\Local Settings\Temp
.15 As mentioned, the OleDbProvider will always execute in the context of the user who initialized it, in this case User/User.
.16 User/User has no rights on this folder (C:\Documents and Settings\Admin\Local Settings\Temp).
If running FileMon when the SQL is executed, we can see the following:
(Actually, try using Process Monitor - http://technet.microsoft.com/en-us/sysinternals/bb896645)
sqlservr.exe:000 QUERY INFORMATION C:\DOCUME~1\Admini~1\LOCALS~1\Temp ACCESS DENIED Attributes: Error
So to summarize so far:
The SQL Server service is started as Admin/Admin, when the select is made, the OleDb provider is invoked by User/User.
Now the OleDb provider attempts to create a temporary DSN in the temp directory. This will be the temp directory for the SQL Server service (Admin/Admin)
but the user (in this case User/User) does not have write permissions on this folder. And the error occurs.
There are two ways to resolve this.
Option 1:
Log out of the machine and log in as the account that starts the SQL Server Service (in this case Admin/Admin) then start a command prompt
and type “set t” (no quotes), this will show something like:
TEMP=C:\DOCUME~1\Admin\LOCALS~1\Temp
TMP=C:\DOCUME~1\Admin\LOCALS~1\Temp
these are the environment variables set for %TEMP% and %TMP%, so go to that folder and right click and select Properties -> Security,
then add the user, in this case User/User, note that the default for the user is Read&Execute/List Folder Content/Read, this not enough, you have to select Write as well.
Log out, and log in again as User/User and rerun the command from SSMS. This time it should work.
Option 2:
Log on as Admin and change the TEMP and TMP variable to, for example, C:\Temp, basically this moves the Temp directory out of the Documents and Settings folder.
However, you must restart the SQL server for this to take effect.
So basically, what happens is that when SQL Server starts, it uses the Temp folder of the startup account (Admin/Admin) but the MICROSOFT.JET.OLEDB.4.0 will always execute
as the user who calls the SQL command (User/User) and this will fail unless this user does not have Write access to that temp folder.
Without knowing all setups out there, perhaps option 2 is the preferred solution since with option 1, you will have to add ALL the users that will invoke the provider which may not be practical.
Also, when changing the startup account for the SQL Server service, then the TEMP directory for that account will be used, and you will see the error again until you, again, give write permissions for all the users on this TEMP folder...or a user group (preferred).

What mstrConnection should I use on a webpage to access local SQL Server Express (localhost\SQLEXPRESS)?

Would the following suffice?
Dim mstrConnection As String =
"workstation id=COMPUTER;packet size=4096;data source=localhost\SQLEXPRESS;
integrated security=false;user id=x309-PC\x309;password=abc"
You should be able to get away with a simpler connection string like the following:
Data Source=(local)\SQLExpress;Initial Catalog=myDatabaseName;User ID=myUsername;Password=myPassword;
You also need to make sure in the SQL server security logins you have both mapped the user to a SQL login as well as given the user rights to the database you are interacting with. You can download MS SQL management studio express 2008 to view and set these settings.

How do you setup a linked server to an Oracle database on SQL 2000/2005?

I am able to create and execute a DTS package that copies tables from a remote Oracle database to a local SQL server, but want to setup the connection to the Oracle database as a linked server.
The DTS package currently uses the Microsoft OLE DB Provider for Oracle with the following properties:
Data Source: SERVER=(DESCRIPTION=(ADDRESS=(PROTOCOL=TCP)(HOST=10.1.3.42)(PORT=1521))(CONNECT_DATA=(SERVICE_NAME=acc)));uid=*UserName*;pwd=*UserPassword*;
Password: UserPassword
User ID: UserName
Allow saving password: true
How do I go about setting a linked server to an Oracle database using the data source defined above?
I was able to setup a linked server to a remote Oracle database, which ended up being a multi-step process:
Install Oracle ODBC drivers on SQL Server.
Create System DSN to Oracle database on SQL Server.
Create linked server on SQL server using System DSN.
Step 1: Install Oracle ODBC drivers on server
a. Download the necessary Oracle Instant Client packages: Basic, ODBC, and SQL*Plus (optional)
b. Unzip the packages to a local directory on the SQL server, typically C:\Oracle. This should result in a [directory] like C:\Oracle\instantclient_10_2, which will be the value of [directory] referenced in the rest of this answer.
c. Create a text file named tnsnames.ora within the instant client [directory] that contains the following:
OracleTnsName =
(
DESCRIPTION=
(
ADDRESS = (PROTOCOL=TCP)(HOST=10.1.3.42)(PORT=1521)
)
(
CONNECT_DATA = (SERVICE_NAME=acc)
)
)
Note: Actual HOST, PORT, and SERVICE_NAME will vary based on Oracle server you are establishing a connection to. This information can often be found using the Oracle network client tools under the listeners.
The OracleTnsName can be any name you want to assign to the Oracle data source, and will be used when setting up the system DSN. You can also use the syntax above to define multiple TNS names in the same tnsnames.ora file if desired.
d. Add the [directory] to the system PATH environment variable.
e. Create a new system environment variable named TNS_Admin that has a value of [directory]
f. Execute the [directory]\odbc_install.exe utility to install the Oracle ODBC drivers.
g. It is recommended that you reboot the SQL server, but may not be necessary. Also, you may want to grant security permissions to this directory for the SQL server and SQL agent user identities.
Step 2: Create a System DNS that uses the Oracle ODBC driver
a. Open the ODBC Data Source Administrator tool. [ Administrative Tools --> Data Sources (ODBC) ]
b. Select the System DSN tab and then select the Add button.
c. In the drivers list, select Oracle in instantclient {version}. (e.g. 'Oracle in instantclient 10_2') and then select Finish button.
d. Specify the following:
Data Source Name: {System DSN Name}
Description: {leave blank/empty}
TNS Service Name: should have the OracleTnsName you defined in the tnsnames.ora file listed, select it as the value.
User ID: {Oracle user name}
e. Select Test Connection button. You should be prompted to provide the {Oracle user password}. If all goes well the test will succeed.
Step 3: Create linked server in SQL to the Oracle database
Open a query window in SQL server and execute the following:
EXEC sp_addlinkedserver
#server = '{Linked Server Name}'
,#srvproduct = '{System DSN Name}'
,#provider = 'MSDASQL'
,#datasrc = '{System DSN Name}'
EXEC sp_addlinkedsrvlogin
#rmtsrvname = '{Linked Server Name}'
,#useself = 'False'
,#locallogin = NULL
,#rmtuser = '{Oracle User Name}'
,#rmtpassword = '{Oracle User Password}'
Note: The {Linked Server Name} can be anything you want to use when referencing the Oracle server, but the {System DNS Name} must match the name of the system DSN you created previously.
The {Oracle User Name} should be the same as the User ID used by the system DSN, and the {Oracle User Password} should be the same as you used to successfully test the ODBC connection. See KB 280106 for information on troubleshooting Oracle linked server issues.
Querying the Oracle linked server
You may use OPENQUERY to execute pass-through queries on the Oracle linked server, but be aware that for very large recordsets you may receive a ORA-01652 error message if you specify a ORDER BY clause in the pass-through query. Moving the ORDER BY clause from the pass-through query to the outer select statement solved this issue for me.
I had the same problem. I was on the phone with Microsoft for hours, and they did not have a solution. None of those "connection timeout" settings helped me.
To resolve it, I created a DTS job that runs a proc which only updates the time on one row, in one column, every two minutes. Then I setup a replication between SQL Server and Oracle, scheduled to replicate that single cell change, from SQL to Oracle, every 3 minutes. It keeps the connection alive!