Connecting to integrated SQL Server in Visual Studio 2016 - vb.net

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.

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.

Import Data to Excel Using SQL/OLE DB

I'm trying to recreate an excel file that I had found that imported data into a table using an OLE DB Query Connection that made use of a SQL server. When I go to the connection properties of the connection I'm trying to recreate, there's no connection file and the connection type states that it is an OLE DB Query. It has a lengthy connection string with the information of the SQL server and then the SQL command text that tells the query basically what to search for.
I am using the 2010 v. of Excel so I go to Data > From Other Sources > Data Connection Wizard > Other/Advanced....
I have no idea where to go from there. I've tried clicking on the OLE DB for SQL but it doesn't seem like it's right as it'll delete itself because there's apparently too much data from the query and it'll take too long to load.

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.

ODBC Linked server in sql 2005 doesn’t work from remote box

I have a dev workstation with sql 2005 installed and in it I created a linked server to a odbc connection to a clarion database. I can run select statements against it inside sql Mgt studio. When I take a second workstation and connect to the sql on the first box using sql mgt studio, then try the exact same query I get
OLE DB provider "MSDASQL" for linked server "liveclarion" returned message "[SoftVelocity Inc.][TopSpeed ODBC Driver][ISAM]ISAM Table Not Found".
Any thoughts? It appears to have the same functionality on a second sql server. No remote sql mgt studio connect success in queries against my linked ODBC clarion DB.
All done with windows authentication and the same AD user.
The error returned by the ODBC driver is "SAM table not found".
So I'm assuming you have a table called SAM - presumably in a table called Sam.Tps?
I'm wondering if you need to set a path to that file - ie if there's some difference in path or file name validity between your two tests. One assumes not, but I'd look in that direction first.

how to access sql server from asp page

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