I am trying to access SQL Server 2019 with System.Data.OleDB but I get this error:
System.Data.OleDb.OleDbException: [DBNETLIB][ConnectionOpen (Connect()).]SQL Server does not exist or access denied.
However, I am able to connect via SqlConnection.
What am I missing?
Any other configuration needed for OleDb connection to work?
I have tested using both UserID and password as well as integrated security.
I am testing in own laptop/home wifi and accessing local database, also enable tcp port 1433 specifically in window firewall.
This is my code:
var connectionString = "Provider=SQLOLEDB;Data Source=localhost;Initial Catalog=TestDB;User ID=sa;Password=sa"
//var connectionString = "Provider=SQLOLEDB;Data Source=localhost;Initial Catalog=TestDB;Integrated Security=SSPI"
OleDbConnection connection = new OleDbConnection(connectionString);
using (connection)
{
OleDbCommand cmd = new OleDbCommand("select * from TestTable", connection);
OleDbDataAdapter da = new OleDbDataAdapter(cmd);
DataSet ds = new DataSet();
da.Fill(ds);
}
The following shows how to connect to SQL Server using System.Data.OleDb.
According to Microsoft OLE DB Driver for SQL Server
Different generations of OLE DB Drivers:
There are three distinct generations of Microsoft OLE DB providers for
SQL Server.
Microsoft OLE DB Provider for SQL Server (SQLOLEDB) The Microsoft OLE DB Provider for SQL Server (SQLOLEDB) still ships as part of
Windows Data Access Components. It is not maintained anymore and it is
not recommended to use this driver for new development.
SQL Server Native Client (SNAC) Starting in SQL Server 2005 (9.x), the SQL Server Native Client (SNAC) includes an OLE DB provider
interface (SQLNCLI) and is the OLE DB provider that shipped with SQL
Server 2005 (9.x) through SQL Server 2012 (11.x).
It was announced as deprecated in 2011 and it is not recommended to
use this driver for new development. For more information about the
SNAC lifecycle and available downloads, refer to SNAC lifecycle
explained.
Microsoft OLE DB Driver for SQL Server (MSOLEDBSQL) OLE DB was undeprecated and released in 2018.
The new OLE DB provider is called the Microsoft OLE DB Driver for SQL
Server (MSOLEDBSQL). The new provider will be updated with the most
recent server features going forward.
Note:
To use the new Microsoft OLE DB Driver for SQL Server in existing
applications, you should plan to convert your connection strings from
SQLOLEDB or SQLNCLI, to MSOLEDBSQL.
One can find the connection string here.
Before proceeding, it's necessary to identify the server name where SQL Server is installed, and the instance name (if one exists).
To find the server name:
Open a cmd window, and type: hostname
To find the SQL Server instance name:
Option 1:
Open a cmd window, and type:
sc query | find /i "SQL Server"
You'll see something like the following: DISPLAY_NAME: SQL Server (SQLEXPRESS). The SQL Server instance name is within (). In this case, the SQL Server instance name is: SQLEXPRESS
Option 2
Open PowerShell, and run the following:
Get-CimInstance -Namespace Root\Microsoft\SqlServer -Query "Select Name from __Namespace where Name like 'ComputerManagement%'" | ForEach-Object { $sqlMgmtVer = $_.Name; Get-CimInstance -Namespace Root\Microsoft\SqlServer\$sqlMgmtVer -Class FileStreamSettings |Select-Object InstanceName }
Option 3
Open PowerShell, and run the following:
Get-CimInstance -Namespace Root\cimv2 -Query "Select DisplayName from Win32_Service where DisplayName like 'SQL Server%'" | ForEach-Object {$dName = $_.DisplayName; if ($dName -match "^SQL Server \((?<instanceName>.*)\)$") { $matches["instanceName"]; }}
Now that we've gathered the necessary information, try the following:
// '.' can be used instead of "localhost" or "127.0.0.1"
// SQL Server instance name = SQLExpress
private string _connectionStr = #"Provider=MSOLEDBSQL;Server=.\SQLExpress;Database=TestDB;UID=test;PWD=mySecretPassword;";
public DataTable GetProductInfo()
{
DataTable dt = new DataTable();
using (OleDbConnection con = new OleDbConnection(_connectionStr))
{
using (OleDbDataAdapter da = new OleDbDataAdapter("select * from Product", con))
{
da.Fill(dt);
return dt;
}
}
}
Resources:
Microsoft OLE DB Driver for SQL Server
Connection Strings - SQL Server OLE DB
System.Data.OleDb Namespace
Filtering output using "Where-Object" in Powershell
Windows PowerShell: Extracting Strings Using Regular Expressions
Powershell: The many ways to use regex
Chapter 7 - Working with WMI
Related
The following script works within a SQL Server 2014 Management Studio in a Stored Procedure but not when I call the stored proc via a C# app .NET Framework 4.8.
SQL Code:
create proc getData
as
Insert INTO tmpLeaveImport ([CarName], Year, Make , Model)
SELECT * FROM OPENROWSET('Microsoft.ACE.OLEDB.15.0',
'Excel 12.0;Database=E:\Cars\Cars.xlsx',
'SELECT * FROM [Car Report$]')
From C# I get the following error:
System.Data.SqlClient.SqlException: 'Cannot initialize the data source
object of OLE DB provider "Microsoft.ACE.OLEDB.15.0" for linked server
"(null)". OLE DB provider "Microsoft.ACE.OLEDB.15.0" for linked server
"(null)" returned message "Unspecified error".'
When this code is executed in C#:
//Tried the conn strign with Integrated Security=yes and SSPI
string ConnString = #"Data Sournce=MySQLServerDB;Initial Catalog=DBName;Integrated Security=true;";
using (SqlConnection conn = new SqlConnection(ConnString))
{
using (SqlCommand cmd = conn.CreateCommand())
{
conn.Open();
cmd.CommandText = "getData";
cmd.CommandType = CommandType.StoredProcedure;
cmd.ExecuteNonQuery();
}
conn.Open();
}
Short Version
According to this possibly duplicate question the Excel file may be open. Or this could be a more serious error.
Don't use OPENROWSET to import Excel data into SQL Server. Use a library like ExcelDataReader to read it without using the Access Engine and insert it to the target table with SqlBulkCopy. You'll avoid a lot of pain.
using (var stream = File.Open(filePath, FileMode.Open, FileAccess.Read))
{
using (var reader = ExcelReaderFactory.CreateReader(stream))
{
using (var bcp = new SqlBulkCopy(connString))
{
bcp.DestinationTableName ="SomeTable";
bcp.WriteToServer(reader);
}
}
}
Long Version
In both cases, the stored procedure runs on SQL Server, not on the client. SSMS is just another client as far as SQL Server is concerned. Assuming the same server is used in both cases, what's different is that the account that executes the stored procedure is different in each case.
With SSMS, it's the developer's account which quite often has sysadmin privileges on the server. With C#, the account may be the end user's, or the application pool account that runs a web site, which has very restricted privileges. SQL Server's default service account is a restricted account too.
This matters because the Access Engine is a COM component. To use it, applications need to look it up in the registry, which requires its own permissions. If you search SO for the error you got you'll see questions where the choice of service account affected whether Access Engine can be used or not. In other cases, the file was open.
Another potential problem is that ACE must target the same architecture as any previous Office components installed on a machine. If you have a x86 Office application, you can only install the x86 version of ACE. That's because you can't use COM component created for one architecture from a process that targets another one.
This also means you can't use an x86 ACE in a x64 installation of SQL Server, which is the most common installation option in the last 10+ years.
I'm working on a Windows CE application, and I need to copy server table data to SQL Server CE database (local) using C# programming. I'm using Visual Studio 2008, SQL Server 2008 for the development.
Below is the code I'm working with, but it seems in VS2008 SqlBulkCopy isn't supported. Do we have any alternatives to achieve this functionality?
SqlConnection source = new SqlConnection(Con_s);// server connection string SQL Server
SqlCeConnection destination = new SqlConnection(Con_l);// Local connection string SQL Server CE DB
SqlCeCommand cmd = new SqlCeCommand("DELETE FROM ProductList", destination);
source.Open();
destination.Open();
cmd.ExecuteNonQuery();
cmd = new SqlCommand("SELECT * FROM Products", source);
SqlDataReader reader = cmd.ExecuteReader();
SqlBulkCopy bulkData = new SqlBulkCopy(destination);
bulkData.DestinationTableName = "ProductList";
bulkData.WriteToServer(reader);
bulkData.Close();
destination.Close();
source.Close();
Add: I have included both using System.Data.SqlClient; & using System.Data; in the code
Since I cannot paste image in the comments,I am including it as answer.
SqlBulkcopy is present under System.Data.SqlClient namespace.
Just navigate to SqlBulkcopy namespace,you must get navigated to the below
If not I think your dll is corrupted may be you need to reload new one.
I've been having issues trying to connect mySQL Server MC9190 (barcode scanner) to a SQL Server database and I've been having issues. It works fine when I run on my desktop, but when I try to run it on my pocket PC that runs on Windows CE 6.0 it throws the error:
System.TypeLoadException was unhandled
Message="File or assembly name 'System.Data.SqlClient, Version=3.0.3600.0,Culture=neutral, PublicKeyToken=3BE235DF1C8D2AD3', or one of its dependencies, was not found."
Anyone have any idea how to connect my pocket pc to the database so I can input the data I collect from the scanner into the database? Here is my code when I'm trying to connect to the database:
SqlConnection myConnection = new SqlConnection("Server=*****\\SQLEXPRESS;DATABASE=testing;Trusted_Connection=yes;connection timeout=15;user id=************");
try
{
//open the server
myConnection.Open();
//Insert values passed into the metod
SqlCommand myCommand = new SqlCommand("INSERT INTO test (Part_Number, total, number_of_packs, dunsNumber, serialNumber, truck_number) VALUES (#Part_Number,#total,#number_of_packs,#dunsNumber,#serialNumber,#truck_number)", myConnection);
myCommand.Parameters.AddWithValue("#Part_Number", partNumber);
myCommand.Parameters.AddWithValue("#total", total);
myCommand.Parameters.AddWithValue("#number_of_packs", numOfPacks);
myCommand.Parameters.AddWithValue("#dunsNumber", dunsNumber);
myCommand.Parameters.AddWithValue("#serialNumber", serialNumber);
myCommand.Parameters.AddWithValue("#truck_number", laneNumber);
//execute the query
myCommand.ExecuteNonQuery();
myConnection.Close();
}
As far as I'm aware, you cannot use Express on it. You will need to use Compact.
Here is a tutorial on setting up SQL CE with C# Apps.
http://www.dotnetperls.com/sqlce
Here are the install instructions for CE 6 (MS SQL Compact needs an extra install).
http://msdn.microsoft.com/en-us/library/13kw2t64(v=vs.90).aspx
Edit: --> this is assuming you are trying to use a database on the machine itself. Otherwise this won't be your answer.
I created a new database using SQL Server 2008 R2 by using the Management Studio. The connection says (local) and I am using Windows Authentication (though I installed with mixed mode).
My questions are:
How do I connect to the DB via my C# application -
The only time I ever have done this before I just used VS Menu > Tools > Connect to DB and the drop down saw my database and connected, then right clicked on it and grabbed the connection string for use in connecting. However I'm thinking because its (local) I don't have that option.
As per Q#1 I am assuming the database file is being stored somewhere locally - I am wondering how to find that location and how I can include it with my application
Edit** Per comment: VSMenu-> View-> Server Explorer and then use add connection to connect to your local SQL Server instance and then use the database you created from the databases dropdown, and from advance settings copy the connection string created by the connection dialog
This is what I am looking for but I am missing the step during "add connection" where do I find my SQL Server I created locally? As mentioned before I have no idea where it is stored or how to find it
MSDN has an example in the SQLConnection documentation
using (var connection = new SqlConnection(connectionString))
using (var command = new SqlCommand(queryString, connection))
{
command.Connection.Open();
command.ExecuteNonQuery();
}
You can then optionally use a SqlDataAdapter.
You need to use ADO.NET, which is comprised of a connection object (SqlConnection), command object (SqlCommand), parameters objects (SqlParameter) and data sets (DataSet) or data readers (SqlDataReader).
Read A Beginner's Tutorial for Understanding ADO.NET.
I'm making an ASP.net with c# webapp using VS 2008, and I added a new sql database item to my project. I added tables to the databse. In the database explorer the test connection works. I guess I have two questions. One:In the application, how does one connect to the database using a connection string? or what connection string should I use? Second: How do I add a username and password to the database?
Right now I'm using this connection string in the web.config file, but when I run the app it times out and says it can't make a connection. The error is on the conn.open line.
add name="ReportsConnectionString" connectionString="Data Source=(local); Initial Catalog=REPORTS;Integrated Security=True" providerName="System.Data.SqlClient"
I have this code in one of my page's codebehind.
string sqlquery = "SELECT * FROM reportitems";
using (SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["ReportsConnectionString"].ConnectionString))
{
conn.Open();
using (SqlCommand comm = new SqlCommand(sqlquery, conn))
{
using (SqlDataAdapter adapter = new SqlDataAdapter(comm))
{
DataSet ds = new DataSet();
adapter.Fill(ds, "reportitems");
DataRowCollection dra = ds.Tables["reportitems"].Rows;
foreach (DataRow dr in dra)
{
string DRZ = dr[0].ToString();
//more stuff here
}
}
}
}
Usually SqlServer Express is reachable on your local PC using this syntax for the Data Source parameter yourpcname\SQLEXPRESS. To be sure start Management Studio and look at the Server Name request.
For the security part of your question, I suppose that you don't want the Integrated Security option (Windows User), but you want a SQLServer user. In this case you could use the User ID and Password parameters for the connection string:
Data Source=MYPC\SQLEXPRESS;Initial Catalog=REPORTS;User Id=MYNAME;Password=MYPASS;
However, this works only after you have added this user to the SQLServer.
You could use the interface of Management Studio app or you could execute a script like this
USE [master]
GO
CREATE LOGIN [MYNAME] WITH PASSWORD=N'MYPASS', DEFAULT_DATABASE=[master]
GO
USE [REPORTS]
GO
CREATE USER [MYNAME] FOR LOGIN [MYNAME]
GO
The Integrated Security=True part of the connectionstring means that the server will use the credentials of the app pool running the site, and you don't need to specify username or password. The app pool identiy will, however, need to have access to your database.
Visit http://www.connectionstrings.com/ for a good primer on various ways to set the connection string for various applications. That'll show you why (local) didn't work but .\SQLEXPRESS did and how to add username and password to it. Here's an example lifted from http://www.connectionstrings.com/sql-server-2008
Data Source=myServerAddress;Initial Catalog=myDataBase;User
Id=myUsername;Password=myPassword;
As others have said, you need a SqlExpress engine running as .mdf is not a flat file. It is a SQL server express database file and you need to connect to it.
But what have not said is that a Database in your App_Data folder needs to be attached to the SqlServer instance. This step is only done once in the first connection.
In http://www.connectionstrings.com/sql-server-2008 you will find an example in the "Attach a database file, located in the data directory, on connect to a local SQL Server Express instance" section that looks like this:
Server=.\SQLExpress;AttachDbFilename=|DataDirectory|mydbfile.mdf; Database=dbname;Trusted_Connection=Yes;
Also you can read this: http://msdn.microsoft.com/en-us/library/ms247257.aspx
I believe that you will need to run some scripts and stuff like that to create a user and assign permissions to this user in this database, and then change the connection string (once the database attached), so I don't see a point in having the database in the App_Data folder. I believe it should be better if since the beginning you create your database using the SqlServer tools and connect to it from your application.