Programmatically adding table to Microsoft SQL Server Compact 3.5 Database - c#

We want to add a table programmatically to our local stored Microsoft SQL Server Compact 3.5 Database. The code below creates the table.
using (SqlCeConnection con =
new SqlCeConnection("Data Source=|DataDirectory|\\Database.sdf"))
{
con.Open();
using (SqlCeCommand com =
new SqlCeCommand("create table test (id int not null)", con))
{
Console.WriteLine("Response: " + com.ExecuteNonQuery());
}
con.Close();
}
The code is working fine, but the table isn't listed up in the Server Explorer of the specified database table. We can insert values into the table and read data out of the table.
Do you know any solutions for this problem?
Afterwards we want to add a dynamic datamodel, which we want to use as a provider of our tables.
Thank you in advance.

The use of |DataDirectory| means that you have 2 copies of the file in your project folders.
Your application is using the one in Root\bin\debug.
Your tools are looking in \Root.

Related

Retrieve custom table data with Azure SQL

I have an Azure Web Site, using a free Azure SQL database, and I have installed Umbraco CMS 7.1.1 to develop the site with. I have also created a custom table using Azure's SQL Management feature and I have created a couple of test rows with dummy text. How can I connect to my custom table and display the data on a page?
Usually I work with MySQL and fetching data is relatively easy to do but I'm having trouble converting my code to work with Azure SQL. The following is my code which is almost identical to when I use MySQL, but with this snippet I get the error "Keyword not supported: 'flush interval'". Has anyone been able to fetch custom table data with Azure SQL?
ConnectionStringSettings cs = ConfigurationManager.ConnectionStrings["umbracoDbDSN"];
using(SqlConnection con = new SqlConnection(cs.ToString()))
{
string sql = "SELECT * FROM [dbo].[MyTable]";
con.Open();
using(SqlCommand cmd = new SqlCommand(sql,con))
{
SqlDataReader reader = cmd.ExecuteReader();
}
con.Close();
}
If you are accessing this in an Umbraco-based website and have the tables within the same database that Umbraco is using, you can get the connection string by accessing the ConnectionString property on the DatabaseContext:
using (var con = new SqlConnection(Umbraco.Core.ApplicationContext.Current.DatabaseContext.ConnectionString)) {
// Your code here
}
However, you may find it advantageous to use the built-in PetaPoco support that Umbraco offers. There's a good example of using PetaPoco here: http://creativewebspecialist.co.uk/2013/07/16/umbraco-petapoco-to-store-blog-comments/

by connecting c# and mysql how to drop a db create it again and connect?

after connecting to database in C#
string MyConString2 = "SERVER=localhost;" + "user id=mytest;" + "DATABASE=clusters;" + "PASSWORD=mypass;";
I have an algorithm which I need to after each run of algorithm that will fill the database, drop the database "clusters" of mysql manually and again connect to the empty database and run it again,gaining new data in tables
I want to make it automatically how can I drop or empty my database if exists in C# and then run my algorithm?
Here is example code that works and I think this is what you are talking about, if not, feel free to correct me.
using (var connection = new MySqlConnection("server=localhost;user=root;password="))
{
connection.Open();
var command = connection.CreateCommand();
command.CommandText = "drop schema if exists clusters";
command.ExecuteNonQuery();
command = connection.CreateCommand();
command.CommandText = "create schema clusters";
command.ExecuteNonQuery();
}
Prepare sql query for clearing your DB and test it in f.e. MySQL workbench. Following this, just execute it as you would execute regular query against DB in C#. One way is to clear all the tables in your database by using TRUNCATE statement and the second way is to DROP DATABASE and recreate it.

How can I get SQLite to work in C#

I have installed SQLite and am using the wrapper from: http://sqlite.phxsoftware.com/
I have created my database and table in the server explorer in VS2010 but when I create the connection, I don't understand what to do from there and how to get it to work.
Can someone provide code examples on how to connect to a db, get a table, insert data into the table and select data from a table and output it.
I would really appreciate it.
Thanks
Server Explorer is overkill, SQLite is meant to be simple and light. Just use plain code as follows.
SQLiteConnection connection = new SQLiteConnection("Data source=PATH_TO_YOUR_DB;Version=3");
connection.Open();
SQLiteCommand command = connection.CreateCommand();
command.CommandText = "insert into something values (1,2,3)";
command.ExecuteNonQuery();
connection.Close();
Hope it helps.
OK here is what I did (assuming that you have that s**t installed):
1.-right click on server explorer
2.-then click on add conection
3.-on data source click Change then select sqlite
4.-fill out da details
5.-you are done... you can now add datasets....

C# Sync MS Access database to sql server

I am trying to set up a synchronization routine in C# to send data from a ms access database to a sql server. MS Access is not my choice it's just the way it is.
I am able to query the MS Access database and get OleDbDataReader record set. I could potentially read each individual record and insert it onto SQL Server but it seems so wasteful.
Is there a better way to do this. I know I could do it in MS Access linking to sql server and perform the update easy but this is for end users and I don't want them messing with access.
EDIT:
Just looking at SqlBulkCopy I think that may be the answer if I get my results into DataRow[]
I found a solution in .NET that I am very happy with. It allows me to give the access to the sync routine to any user within my program. It involves the SQLBulkCopy class.
private static void BulkCopyAccessToSQLServer
(CommandType commandType, string sql, string destinationTable)
{
using (DataTable dt = new DataTable())
{
using (OleDbConnection conn = new OleDbConnection(Settings.Default.CurriculumConnectionString))
using (OleDbCommand cmd = new OleDbCommand(sql, conn))
using (OleDbDataAdapter adapter = new OleDbDataAdapter(cmd))
{
cmd.CommandType = commandType;
cmd.Connection.Open();
adapter.SelectCommand.CommandTimeout = 240;
adapter.Fill(dt);
adapter.Dispose();
}
using (SqlConnection conn2 = new SqlConnection(Settings.Default.qlsdat_extensionsConnectionString))
{
conn2.Open();
using (SqlBulkCopy copy = new SqlBulkCopy(conn2))
{
copy.DestinationTableName = destinationTable;
copy.BatchSize = 1000;
copy.BulkCopyTimeout = 240;
copy.WriteToServer(dt);
copy.NotifyAfter = 1000;
}
}
}
}
Basically this puts the data from MS Access into a DataTable it then uses the second connection conn2 and the SqlBulkCopy class to send the data from this DataTable to the SQL Server. It's probably not the best code but should give anyone reading this the idea.
You should harness the power of SET based queries over RBAR efforts.
Look into a SSIS solution to synchronize the data and then schedule the package to run at regular intervals using SQL Server Agent.
You can call an SSIS package from the command line so you can effectively do it from MS Access or from C#.
Also, the SQL Server, the MS Access DB and the SSIS package do not have to be on the same machine. As long as your calling program can see the SSIS package, and the package can connect to the SQL Server and the MS Access DB, you can transfer data from one place to another.
It sounds like what you are doing is ETL. There are several tools that are built to do this and to me, there is little reason to reinvent the functionality. You have SQL Server, therefore you have SSIS. It has a ton of tools for automated transformations, cleanups, lookups, etc. that you can use out of the box.
Unless this is a real cut-and-dry data load and there is absolutely no scope for the complexity of the upload to increase later on (yeah, right!) I would go with a tried and tested ETL tool.
If SQL Server Integration Services isn't an option, you could write out to a temporary text file the data that you read from Access and then call bcp.exe to load it to the database.
I have done something like this before.
I used
OleDbConnection aConnection = new OleDbConnection(String.Format("Provider=Microsoft.Jet.OLEDB.4.0;Data Source={0}", fileName));
aConnection.Open();
to open the access db. Then
OleDbCommand aCommand = new OleDbCommand(String.Format("select * from {0}", accessTable), aConnection);
OleDbDataReader aReader = aCommand.ExecuteReader();
to execute the read from the table. Then
int fieldCount = aReader.FieldCount;
to get the field count
while (aReader.Read())
to loop the records and
object[] values = new object[fieldCount];
aReader.GetValues(values);
to retrieve the values.
There are several ways to sync but it can give a problem when you change a field name in sql server or add a new column or delete. The best option would be:
Create connections for sql server and oledb.
Write custom query to fetch record from one connection and save it to another.
Before executing make sure to program in a way that you update all table definitions.
In my case this helped in a way because the load on sql server became down.
can you not transfer Access file to the server and delete it once sync is complete?
You can create windows service for that..

Getting a DataSet from an SQL Express Server C#

How can I get a DataSet with all the data from a SQL Express server using C#?
Thanks
edit: To clarify, I do want all the data from every table. The reason for this, is that it is a relatively small database. Previously I'd been storing all three tables in an XML file using DataSet's abilities. However, I want to migrate it to a database.
You can use the GetSchema method to get all the tables in the database and then use a data adapter to fill a dataset. Something like this (I don't know if it compiles, I just paste some code and change it a bit):
DbProviderFactory factory = DbProviderFactories.GetFactory("System.Data.SqlClient");
DataTable tables = null;
DataSet database = new DataSet();
using (DbConnection connection = factory.CreateConnection())
{
connection.ConnectionString = "Data Source=(local);Initial Catalog=Northwind;Integrated Security=True";
string[] restrictions = new string[4];
// Catalog
restrictions[0] = "Northwind";
// Owner
restrictions[1] = "dbo";
// Table - We want all, so null
restrictions[2] = null;
// Table Type - Only tables and not views
restrictions[3] = "BASE TABLE";
connection.Open();
// Here is my list of tables
tables = connection.GetSchema("Tables", restrictions);
// fill the dataset with the table data
foreach (DataRow table in tables.Rows)
{
string tableName = table["TABLE_NAME"].ToString();
DbDataAdapter adapter = factory.CreateDataAdapter();
DbCommand command = factory.CreateCommand();
command.Connection = connection;
command.CommandType = CommandType.Text;
command.CommandText = "select * from [" + tableName + "]";
adapter.SelectCommand = command;
adapter.Fill(database, tableName);
}
}
EDIT:
Now I refactored it a bit and now it's working as it should. The use of DbConnection and DbProviderFactories is for database engine abstraction, I recommend using it so you can change the database engine changing this line and the connection string:
DbProviderFactory factory = DbProviderFactories.GetFactory("System.Data.OracleClient");
The GetSchema method will retrive all tables from your database to a DataTable and then we get all the data from each table to the DataSet using the DataAdapter.
I think you need to narrow down the question somewhat... All the data? You mean, all the data in every table in every database? Well, the only answer to that is, a lot of code.
To connect to and talk to a SQL Server Express database engine, use the classes in the System.Data.SqlClient namespace, namely:
SqlConnection: Connect to the database
SqlCommand: Talk to the database
SqlDataReader: Iterate over data retrieved from the database
You can check the MSDN pages for all of these classes by clicking on the links above.
Here are some overview-links with more information:
CodeProject: Beginners guide to accessing SQL Server through C#
DevHood: Accessing SQL Server Data in C# with ADO.NET
Note that by and large, you use a SQL Server Express database engine the same way as the full SQL Server product, the difference is more in the tools you get with it, and some limitations in the express engine. Other than that you can just use the classes and language that you would use for a normal SQL Server database engine installation.
If this post didn't answer your question, please elaborate, and you have a higher chance of getting the answer you seek.
This can be done by using dataAdapter class.

Categories

Resources