Copy a whole table from a SQL Server CE database to another - c#

I'm developing a C# application and I want to copy a whole table from a SQL Server CE database to another programmatically. I know I can use this command in SQL Server, but I'm not sure how to use two database connections in one query in C#.
Select * into DestinationDB.dbo.tableName from SourceDB.dbo.SourceTable
Thanks in advance.

You wouldn't do it the same way as in SQL Server because there's no single server that manages both databases. Your app is the only thing that links the two databases so the the data has to go through your app. You're trying to do it the wrong way and that's why you can't find a solution: you're looking for the wrong thing.
There are examples of this out there. I know, because I've written more than one myself. You simply need to use a data adapter to populate a DataTable from the first database and then a data adapter to save the contents of that DataTable to the second database. If the data sources are the same type then you can even use just one data adapter because the SelectCommand and InsertCommand can have different connections.
using (var adapter = new SqlDataAdapter("SELECT statement here", "source connection string here"))
using (var destinationConnection = new SqlConnection("destination connection string here"))
using (var insertCommand = new SqlCommand("INSERT statement here", destinationConnection))
{
// Add parameters to insertCommand here.
adapter.InsertCommand = insertCommand;
// Leave the RowState of all DataRows as Added so they are ready to be inserted.
adapter.AcceptChangesDuringFill = false;
var table = new DataTable();
// Retrieve data from source and save to destination.
adapter.Fill(table);
adapter.Update(table);
}
That example uses SqlClient but it works the same for any provider, including SqlServerCe.

Related

DataSource for DataGridView is not showing the data of the table

Within Visual Studio 2017 I just created a DataGridView and linked a DataSource to it. It asked me for a connection string (which I gave). It showed the table from the database that I wanted in the DataGridView and it created automatically the correct columns within the DataGridView for me.
But for some reason when I start the application it does not show any data. I assume it connects to the database correctly otherwise it couldn't possibly know the name of my table and the columns within it. So how comes it sees my table but does not get the data?
So to test this I tried to make a simple RadDropDownList with help of the guide "LINK" But by following the steps for "Data binding at design time" I get the same exact result. It seems like it connects correctly but then it shows no data.
Does anyone knows why Visual Studio connects to my database with help of a DataSource but then does not gets any data from the table? Am I perhaps missing something?
Added:
I am using Microsoft SQL Server.
Yes, I have checked if the table contains data.
Try this:
string connectionString = "Data Source=.;Initial Catalog=pubs;Integrated Security=True"; // put your connection string
string sql = "SELECT * FROM Authors"; // change your table name
SqlConnection connection = new SqlConnection(connectionString);
SqlDataAdapter dataadapter = new SqlDataAdapter(sql, connection);
DataSet ds = new DataSet();
connection.Open();
dataadapter.Fill(ds, "Authors_table");
connection.Close();
dataGridView1.DataSource = ds; // put your gridview name
dataGridView1.DataMember = "Authors_table";

Inner Join two databases to import data - SQL C#

I've created a Winforms app in C#. I do have both my Datasources listed as Datasets.
LOTSDataSet = Source Info
webbitdbdataset = Destination Dataset.
These are connected with LOTSConnectionString and WebbitConnectionString.
Anyway I have the code shown below that I am getting a connection error on, when I try to import data from LOTS to Webbit.
SqlConnection lotscon = new SqlConnection(PackChecker.Properties.Settings.Default["LOTSConnectionString"].ToString());
using (OleDbConnection con = new OleDbConnection(PackChecker.Properties.Settings.Default["WebbitConnectionString"].ToString()))
{
string strgetloc = #"INSERT INTO tblinstitution (
dispenseinstid, institutionname )
SELECT NEWinstitution.institutionid, NEWinstitution.institutionname
FROM NEWinstitution LEFT JOIN tblinstitution ON NEWinstitution.institutionid
= tblinstitution.dispenseinstid
WHERE (((tblinstitution.institutionid) Is Null));";
using (OleDbCommand cmd = new OleDbCommand(strgetloc, con))
{
lotscon.Open();
con.Open();
cmd.ExecuteNonQuery();
con.Close();
lotscon.Close();
}
}
Trying to "OPEN CONNECTION" for both connections was just something I tried.. I guess knowing it was going to fail, but I wanted to try before I asked on here.
The command is attached to the OLEDB connection to Webbit, thus I'm getting an exception based on 'cannot find LOTS server'
Prior to running the query I do run a connection checker, which opens both connections and "tries and catches" both connections to make sure they are valid connections.
Using Access the query does work, so I know the issue 100% is trying to open these connections to two databases!
Any direction would be appreciated.
Gangel

What is the best way for me to connect to a offline database through C#

I have an application that needs to store loads of data in a table format. I want something easy to configure, which is also in built with C#.NET. I don't want to have to include additional DLL files.
Also some links to tutorials, explaining the connection process and querying would be great. I'm assuming this is just like PHP, but which database type do I need?
It needs to be able to hold a lot of data and the ability to perform backups would be nice.
I'm not sure what you mean by "built in with C#.NET", but SQL Server Express comes with Visual Studio.
If you're looking for "a self-contained, embeddable, zero-configuration SQL database engine", you could try System.Data.SQLite.
If you want an offline database you could use SQL Server CE, as its a in-process database that does not require being attached to a server instance, which is really what you want then. Here is an example in C# on how you would connect, and populate a data table to manipulate some data.
// this connectionstring can also be an absolute file path
string connectionString = "Data Source=|DataDirectory|\mydatabase.sdf";
using (SqlCeConnection connection = new SqlCeConnection(connectionString)) {
try {
connection.Open();
}
catch (SqlCeException) {
// connection failed
}
using (SqlCeDataAdapter adapter = new SqlCeDataAdapter("SELECT * FROM <table>", connection)) {
using (DataTable table = new DataTable("<table>")) {
adapter.Fill(); // Populate the table with your select statement
// do stuff with the datatable
// example:
foreach (DataRow row in table.Rows) {
row["mycolumn"] = "somedata";
}
table.AcceptChanges();
}
}
}
You can even use commands instead of data tables
using (SqlCeCommand command = new SqlCeCommand("DELETE FROM <table> WHERE id = '0'", connection)) {
command.ExecuteNonQuery(); // executes command
}
Have a look at the ease of SQL Server Compact
Not build-in but easily added, no install and free.

How to load SQL Server DB into dataset?

I want to load the entire database (SQL Server) I have into a dataset so that I can work with several tables and their relationships. I know this might be frowned upon, but how can I do this (I will be using DataRelation and Table objects)?
Thanks
Unless I'm missing something this should just be a simple case of generating a dataset and then altering the Fill methods to remove the WHERE portion. Then ensure you call the fills in the right order (master, then detail) to ensure you maintain the referential integrity.
You can run this... but don't expect to have a db or app server after.
using (SqlConnection conn = new SqlConnection("YourConnectionString"))
{
using (SqlCommand command = new SqlCommand("exec sp_msforeachtable 'select * FROM ?'", conn))
{
conn.Open();
DataSet ds = new DataSet();
command.Fill(ds);
}
}
Read some article about in memory Database.
# Randolph Potter idea is an option - you can get the list of tables from the server, and then iterate on the list and load all the tables. I guess you can do that same about FK and relations.
you can probably do it automatically using the designer - using drag and drop from the server explorer to a dataset (VS2008), and with a little code load the entire thing into memory.
I suppose you could do multiple selects within a single stored procedure and then fill a dataset.
using (SqlConnection conn = new SqlConnection("YourConnectionString"))
{
using (SqlDataAdapter command = new SqlDataAdapter("usp_YourStoredProcedure", conn))
{
command.CommandType = CommandType.StoredProcedure;
conn.Open();
DataSet ds = new DataSet();
command.Fill(ds);
}
}
I would agree with the other comments here that unless your database is tiny this is a really bad idea.

How do I pull data from my old server to my SQL server?

I want to write a code that transfers data from on server to my SQL Server. Before I put the data in, I want to delete the current data. Then put the data from one to the other. How do I do that. This is snippets from the code I have so far.
string SQL = ConfigurationManager.ConnectionStrings["SQLServer"].ToString();
string OLD = ConfigurationManager.ConnectionStrings["Server"].ToString();
SqlConnection SQLconn = new SqlConnection(SQL);
string SQLstatement = "DELETE * FROM Data";
SqlCommand SQLcomm = new SqlCommand(SQLstatement, SQLconn);
SQLconn.Open();
OdbcConnection conn = new OdbcConnection(OLD);
string statement = "SELECT * FROM BILL.TRANSACTIONS ";
statement += "WHERE (TRANSACTION='NEW') ";
OdbcCommand comm = new OdbcCommand(statement, conn);
comm.CommandTimeout = 0;
conn.Open();
SqlDataReader myDataReader = SQLcomm.ExecuteReader();
while (myDataReader.Read())
{
//...
}
SQLconn.Close();
SQLconn.Dispose();
Depending on which version of SQL Server you are using, the standard solution here is to use either DTS (2000 and before) or SSIS (2005 and on). You can turn it into an executable if you need to, schedule it straight from SQL Server, or run it manually. Both tools are fairly robust (although SSIS much more so) with methods to clear existing data, rollback in case of errors, transform data if necessary, write out exceptions, etc.
If at all possible I'd try and do it all in SQL Server. You can create a linked server to your other database server. Then simply use T-SQL to copy the data across - it would look something like...
INSERT INTO new_server_table (field1, field2)
SELECT x, y
FROM mylinkedserver.myolddatabase.myoldtable
If you need to do this on a regular basis or clear out the data first you can do this as part of a scheduled task using the SQL Agent.
If you only need to import the data once, and you have a lot of data, why not use the "BULK INSERT" command? Link
T-SQl allows you to insert data from a select query. It would look something like this:
insert into Foo
select * from Bar;
As long as the field types align this will work - otherwise you will have to massage the data from Bar to fit the fields from Foo.
When you need to do this once, take a look at the database publishing wizard (just google) and generate a script which does everything.

Categories