SQL Server to SQL Server CE table data copy using SqlBulkCopy - c#

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.

Related

Not able to connect access database to visual studio

I am trying to conncet access database to my visual studio but i face this type of error "The Microsoft.ACE.OLEDB.12.0" provider is not registered on the local machine.
I look at some solutions on google i got that after downloading Microsoft Access Database Engine on Local machine we are able to connect database.But i still face this problem. So What should i do for it? .And i am using Windows10 but i use Ms office 2007 and my system is 64-bit.enter image description here
You don't mention if you planning to use the x32 bit or x64 version of access.
So, assuming you downloaded the access data engine? You have to choose or decide WHICH bit size version you wish to use.
That download can be found here:
https://www.microsoft.com/en-ca/download/details.aspx?id=13255
And you have two choices:
Ok, next up?
You MUST set and FORCE your project to the correct bit size.
that is this project setting in VS.
So, if you using x32 version, then use x86 version, and if adopting x64 version, then set your project to x64.
So, don't use "any" for your project setting - you have to force the issue.
So, try setting up a connection. You have two choices:
Use the ODBC provider,
or
Use the oleDB provider
So, ok, ODBC? then that connection setting should look like this:
For odbc, the connecton string should look like this:
Driver={Microsoft Access Driver (*.mdb, *.accdb)};
dbq=C:\TEST\test444.accdb;uid=Admin
for oleDB, the connection string should look like this:
Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\test\test45.accdb
And in both cases, you can as a normal rule, leave the password blank.
Assuming you used the project settings, say here:
(and you can use the connection string builder in above. BUT BE VERY carefull, if you are running access x64, then the test connection WILL ALWAYS ALWAYS fail, since VS is a x32 bit applcation, but if you run your code, and the project was forced to x64 bits, then the connection will work DISPITE VS and the test connection telling you it does not.
So, to use the above ODBC connection, we have this:
using (OdbcConnection conn = new OdbcConnection(Properties.Settings.Default.AccessODBC))
{
string strSQL =
"SELECT * FROM tblHotels ORDER BY HotelName";
using (OdbcCommand cmdSQL = new OdbcCommand(strSQL, conn))
{
conn.Open();
DataTable rstData = new DataTable();
rstData.Load(cmdSQL.ExecuteReader());
dataGridView1.DataSource = rstData;
}
}
And for oledb, we would have this:
using (OleDbConnection conn = new OleDbConnection(Properties.Settings.Default.AccessDB))
{
string strSQL =
"SELECT * FROM tblHotels ORDER BY HotelName";
using (OleDbCommand cmdSQL = new OleDbCommand(strSQL, conn))
{
conn.Open();
DataTable rstData = new DataTable();
rstData.Load(cmdSQL.ExecuteReader());
dataGridView1.DataSource = rstData;
}
}
So, which provider to use?
Most use and suggest oleDB.
However, I think using ODBC is not all that bad of a choice. the reason is you can change the connection to sql server, or other database systems, and NOT have to change your provider, but only the connection string.
While you can sort of do the same with oleDB, there is now MUCH better support for ODBC database systems.

Oledb SQL Server does not exist or access denied

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

C# - XLSX to SQL Server - OpenRecordSet not working in C# but works in MS SQL Server Management Studio

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.

Connecting VS Project to SQL Server [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 4 years ago.
Improve this question
TL;DR so you stop putting this on hold:
Visual Studio will not allow me to create a live connection to a database on an SQL server within a project, even though it can communicate with the server outside of projects. I want it to have a live connection so I can make a website that uses and allows access to the database.
I have Visual Studio 2017 Professional, and Microsoft SQL Server Management Studio 2017.
I have successfully connected a database from the server to Visual Studio such that I can edit the database in Visual Studio, and the server will reflect my changes. However, I cannot get a live connection to the server inside any project. When I import the database into a project, it just creates a copy that does not actually communicate with the server.
I'm thinking I need to create some sort of special object or change some settings in Visual Studio.
Do I need to switch to Enterprise for supported features? It seems rational that the professional edition should be sufficient for this, but if anyone knows how to solve this kind of issue with a different version of Visual Studio or how to create a website connected to a database server through another [hopefully affordable] program, I'm all ears. Thank you!
(This paragraph added later for clarity:) My goal is to create a website using Visual Studio which allows authorized users to edit the database. Unless doing so is a terrible idea, I want to start by making it possible to edit the database on the server using the website made in Visual Studio, and then add the security features. The current database on the server is placeholding junk until the system is satisfactorily set up. It sounds like it may be possible access the database using a website without directly putting it in the Visual Studio project, so I'm looking into the directions provided in the second comment.
The least error-filled solution I managed is as follows, based on #Symon's comment and link. I've tried several things for the first line, and being public void seems to case about 1/30th the errors as being anything else I've tried, which definitely doesn't mean it's actually the right answer. Items in square brackets are removed for security reasons. I entered the credentials for the database exactly as I did in the popup window to connect Visual Studio in general to the database on the server.
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Data.SqlClient;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
public void heresanamespacethingy (string stp)
{
//GET STORED PROCEDURE HERE
string conStr = #"Data Source=[server name]; Initial Catalog=[database name]; User ID=[my user ID]; Password=[my password]";
using (SqlConnection conn = new SqlConnection(conStr))
{
SqlCommand cmd = new SqlCommand();
cmd.Connection = conn;
cmd.CommandText = stp;
conn.Open();
cmd.CommandType = CommandType.StoredProcedure;
cmd.ExecuteNonQuery();
conn.Close();
conn.Dispose();
}
}
The error is
CS0116 A namespace cannot directly contain members such as fields or methods.
I'm using VS Community and can interact with my MS SQL Server just fine. The edition of Visual Studio that you are using isn't going to limit what you can do code-wise. The editions merely add extra features. I have never heard of anyone being limited in their projects because of the edition of Visual Studios that they are using.
As #Kfirprods stated, it may be very helpful for you to manage your Server/Databases with Microsoft SQL Server Management Studio 2017 instead of trying to use Visual Studios for everything.
The most common way that I've seen to get your live/current database information and data is to have your C# code call to the live data and pull it. I will have an example of C# calling a stored procedure below. The example only calls a stored procedure, showing how it is possible for you to use C# to connect to SQL Server and alter data. You can also send individual, inline queries through this method. Though, to avoid SQL injection (especially since it's a website) , it'd be better protection to use this method to call Stored Procedures and Views rather than sending inline queries.
This may be a good link to read up on for learning how to start using C# to connect to SQL Server. It's what I used to get started!
I have my SQL Server Management studio connected to my Server/Databases, and my Visual Studio is only concerned about my C# code. It helps keep things separated and organized (for me, anyway).
Here is a sample of a C# method that connects to a SQL Database, and runs a Stored Procedure:
public void CallSproc(string stp)
{
//GET STORED PROCEDURE HERE
string conStr = "Data Source=" + ConfigurationManager.AppSettings["DataSource"] + "Initial Catalog=" + ConfigurationManager.AppSettings["InitialCatalog"] + "Integrated Security=True;";
using (SqlConnection conn = new SqlConnection(conStr))
{
SqlCommand cmd = new SqlCommand();
cmd.Connection = conn;
cmd.CommandText = stp;
conn.Open();
cmd.CommandType = CommandType.StoredProcedure;
cmd.ExecuteNonQuery();
conn.Close();
conn.Dispose();
}
}
Code Explained:
ConfigurationManager.AppSettings[] points to my App.config file and keys (identifiers) where this data is stored. In case the current server is lost, the program doesn't require a re-compile. The config file just needs altered to point to the right location.
The variable stp is a string that is passed from another method which holds the name of the stored procedure (ex. "stpAddNumbers").
conStr is the connection string that tells the SqlConnection() call what Server and database to connect to.
conn.Open(); opens the connection to the SQL Server itself.
cmd.CommandType = CommandType.StoredProcedure; tells the code that you're calling for a stored procedure.
cmd.ExecuteNonQuery(); executes the stored procedure and the results are returned.
CS0116 A namespace cannot directly contain members such as fields or methods:
With the code you have shown along with the error message, you don't seem to have a namespace at all. To fix this, simply wrap your method in a namespace. Like so:
...
using System.Threading.Tasks;
namespace HeresANameSpace
{
class ThisIsAClass
{
public void HeresAMethod (string stp)
{
//GET STORED PROCEDURE HERE
string conStr = #"Data Source=[server name]; Initial Catalog=[database name]; User ID=[my user ID]; Password=[my password]";
using (SqlConnection conn = new SqlConnection(conStr))
{
SqlCommand cmd = new SqlCommand();
cmd.Connection = conn;
cmd.CommandText = stp;
conn.Open();
cmd.CommandType = CommandType.StoredProcedure;
cmd.ExecuteNonQuery();
conn.Close();
conn.Dispose();
}
//End of HeresAMethod()
}
//End of HeresAClass
}
//End of HeresANamespace
}
When starting from a blank Code file, you need to write in the namespace , classs and methods . A method goes inside of a class, a class goes inside of a namespace.

Unable To Connect using Server Explorer

I'm in Visual Studio 2013, using SQL Server Express 2012, on Windows 7 OS.
With C# code, I CAN connect to the database and query. For example:
using (SqlConnection sqlConnection = new SqlConnection("server=MYSERVER\\SQLEXPRESS; Trusted_Connection=yes; database=MyDatabase; connection timeout=30"))
{
using (SqlCommand cmd = new SqlCommand())
{
cmd.CommandText = "SELECT count(*) FROM tblData";
cmd.Connection = sqlConnection;
sqlConnection.Open();
int count = (int)cmd.ExecuteScalar();
Console.WriteLine(count); // I get the correct answer.
}
}
That works. My problem is that if I use Server Explorer within Visual Studio, I cannot connect to the database via that route. In the Add Connection, MyServer does appear in the server dropdown, but the database dropdown is empty. When I click Test Connection or OK (leaving Database empty or entering MyDatabase), I get the error: Server was not found or was not accessible.
So I can connect via C# code, but not with Server Explorer. What am I missing?
Thanks.
You have a named instance (SQLExpress) of the SQL Server. In the connections window, try typing in the server name as:
MYSERVER\SQLEXPRESS

Categories