I am creating a application and I want to use a local database stored on the clients local machines. I am debating over if I should use SQLITE or is there something in Visual Studio to help me. The other thing is that I want to create the database programmatically in the users directory when the application is launched.
I am see a few things online but the articles were all about SQL Server stuff and that is not want I want to do with this application. All data will need to be stored on the local machine.
You can use SQL Server Compact, which has tooling in Visual Studio. It's syntax-compatible with SQL Server, but stores its data in a local file, which you can create on the fly (at app startup, for example).
You can create the SQLite database on the fly with the libraries provided from their website. I have used it in many projects for my personal code, as well as it being used in some of the internal architecture of Data Explorer (IBM Product). Some sample C# to create a database file:
if (!Directory.Exists(Application.StartupPath + "\\data"))
{
Directory.CreateDirectory(Application.StartupPath + "\\data");
}
SQLiteConnection conGlobal;
if (!File.Exists(dbGlobal))
{
conGlobal = new SQLiteConnection("Data Source=" + dbGlobal + ";New=True;Compress=True;PRAGMA synchronous = 1;PRAGMA journal_mode=WAL");
conGlobal.SetExtendedResultCodes(true);
firstRun = true;
}
else
{
conGlobal = new SQLiteConnection("Data Source=" + dbGlobal + ";Compress=True;PRAGMA synchronous = 1;PRAGMA journal_mode=WAL");
conGlobal.SetExtendedResultCodes(true);
}
try
{
conGlobal.Open();
}
catch (Exception)
{
//do stuff
}
Simply initiating a connection to the file will create it if the new=true is passed as the connection string. Then you can query it and get results just like you would any database.
You also have the ability to password protect the database files to prevent access to them from just opening them with an SQLite-Shell or a different SQLite DB viewer.
For more info on the pragma statements that are being passed in the connection string, see the following: http://www.sqlite.org/pragma.html
I'm not sure about programmatically (that's probably what you meant, right?) creating the database, but SQL Server Compact Edition has served me well in the past for simple apps. It's embedded and even runs in medium trust.
Related
We get .ydb files of firebird database from client. Currenlty we created a DSN with some additional installation/drivers and then access the tables and data inside the files.
We are planning to move this process to azure cloud service (not azure VM) so to avoid creating DSN etc. we need to access the .ydb files from c# code.
I could not open directly using firebird ado.net provider, throwing exceptions.
The below are the steps used to create DSN in the machine. It is working for long time.
Firebird ODBC setup in Windows Server
DSNName-DSNName1,
Driver-IscDbc,
Database-E:\Somefolder\FileName.ydb
Client-C:\ProgramFiles\Firebird\Firebird2_5\WOW64\fbclient.dll
Database Account- SYSDBA
Password - masterkey
Role - SYSDBA
CharSet - None
Then used the below C# code to access the FileName.ydb using the DSN.
using (var connection = new OdbcConnection("DSN=DSNName1"))
{
connection.Open();
var schema = connection.GetSchema("Tables");
var tableNames = new List<string>();
}
Now to modify the above DSN creation process, I added FirebirdSql.Data.FirebirdClient nuget package in the c# solution.
string connectionString = "User=SYSDBA;" + "Password=masterkey;" +
"Database=E:\\Somefolder\\Filename.ydb;" + "Dialect=3;" + "Charset=NONE;" +
"Role=SYSDBA;";
FbConnection fbConn = new FbConnection(connectionString);
fbConn.Open();
var schema = fbConn.GetSchema("Tables");
It throws exception on fbConn.Open(); - Unable to complete network request to host "localhost".
How to open the .ydb files in C# directly without creating a DSN?
The biggest problem you seem to have is that you do not have Firebird server installed or running, so you can't actually connect to it and ask it to open the database file.
You can download Firebird from http://www.firebirdsql.org/en/downloads/ (you will probably need Firebird 2.5) and install it. Then in a project that references FirebirdSql.Data.FirebirdClient you should be able to connect with as little as:
using (var connection = new FbConnection(#"User=username;Password=password;Database=D:\data\DB\database.fdb"))
{
connection.Open();
}
If for some reason you don't want to install Firebird server, you will need to use Firebird embedded (which can also be downloaded from the link above).
You will need to make sure that your application is either running 32 bit or 64 bit, and download the right Firebird embedded package. Put it in the path, or in the folder of your executable. In the URL you need to add ServerType=1 to get Embedded support (the default is ServerType=0):
using (var connection = new FbConnection(#"ServerType=1;User=username;Password=password;Database=D:\data\DB\database.fdb"))
{
connection.Open();
}
I created a small accounting application a while back. It uses SQL Server 2008 as backend data store. Now I realize that SQL Server is too much for such a
small program PLUS it is not very much portable. I mean I want to have this application on my USB stick for easy access anywhere, and SQL Server will not be
available everywhere. So now I want to replace the data store from SQL Server to something portable i.e. MS Access MDB file.
1- Is it a good option or should I use SQL Server express edition?
2- I don't have experience using SQL Express edition. If I use it, would it be needed on any machine where I intend to run my application?
2- What changes should I make in the code to make it compatioble with MDF files (or SQL Express)?
As I said it is quite simple program, it uses connected model to fetch and insert data currently. For example
void bindGrid()
{
try
{
using (SqlConnection con = new SqlConnection(ConnectionString))
{
DataSet set = new DataSet();
SqlDataAdapter da = new SqlDataAdapter();
SqlCommand selectCommand = new SqlCommand("SELECT * FROM Categories ORDER BY name", con);
da.SelectCommand = selectCommand;
da.Fill(set);
this.grdCategories.DataSource = set.Tables[0];
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
Rather than using Access, I would use LocalDB. It should require very few if any changes to your code other than the connection string.
http://blogs.msdn.com/b/sqlexpress/archive/2011/07/12/introducing-localdb-a-better-sql-express.aspx
LocalDB is created specifically for developers. It is very easy to install and requires no management, yet it offers the same T-SQL language, programming surface and client-side providers as the regular SQL Server Express. In effect the developers that target SQL Server no longer have to install and manage a full instance of SQL Server Express on their laptops and other development machines. Moreover, if the simplicity (and limitations) of LocalDB fit the needs of the target application environment, developers can continue using it in production, as LocalDB makes a pretty good embedded database too.
I would recommend SQL CE for small projects.
LocalDB vs SQL Server Compact
There are significant differences between LocalDB and SQL Server Compact:
Execution mode: SQL Server Compact is an in-proc DLL, while LocalDB runs as a separate process.
Disk usage: all SQL Server Compact binaries amount to some 4MBs, while LocalDB installation takes 140MBs.
Features: SQL Server Compact offers core RDBMS functionality like querying, while LocalDB provides a much richer set of features, including Stored Procedures, Geometry and Geography data types, etc.
Context
My appliction uses an SQL database from which it reads my datatables at start of my application. If the application would fail to connect to the SQL DB, I have a local Ms Access .MDB file. I have a separate thread that checks if the local database is outdated.
I have a DataTable which I obtain from my SQL connection --> Verified and working
I can connect to my Access database locally and read from it --> Verified and working
Issue/Question
I'm trying to update my local database by updating it with the DataTable I obtained from my SQL Connection.
public static void UpdateLocalDatabase(string strTableName, OleDbConnection MyConnection, DataTable MyTable)
{
try
{
if (CreateDatabaseConnection() != null)
{
string strQuery = "SELECT * FROM " + strTableName;
OleDbDataAdapter MyAdapter = new OleDbDataAdapter();
OleDbCommandBuilder MyCommandBuilder = new OleDbCommandBuilder(MyAdapter);
MyAdapter.SelectCommand = new OleDbCommand(strQuery, odcConnection);
MyAdapter.UpdateCommand = MyCommandBuilder.GetUpdateCommand();
MyConn.Open();
MyAdapter.Update(MyTable);
MyConn.Close();
}
}
catch { }
}
If I debug this snippet, all variables are what they should be:
strTableName = the correct name for my table
MyConn = #"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=MyLocation;Persist Security Info=True;JET OLEDB:Database Password=MyPassword;"
MyTable = is the correct table that is also used further on by my application
This process runs through without an error and without using the catch but it does not touch my database, it just doesn't do a thing.
Am I dropping the ball here or just missing the obvious, I have no idea but I browsed many articles and apart for showing the MyAdapter.Update(), there doesn't seem to be much more to it.
Any help is welcome.
Thanks,
Kevin
Does your backup database have to be in access? because if you used SQL Compact Edition it'd be much easier to copy between the two?
Yes, it would either mean attaching it with your installer or just ensuring that all client machines have it pre-installed, it is free however.
if this is an issue then all you need to do (I think, not done it myself)
would be to go to your installer projects properties, click prerequisites and then tick SQL compact so that it will be installed before your application can be used, iv done this before with other frameworks and it just pops up a box with the install shield asking whether they want to download the necessary software and its just one click then it should be done for them.
Do you need a hand on using the compact database also?
One negative by the way is it does lack some higher end features but shouldn't affect average database work
EDIT
if you will be using sql CE you can easily make the databse in VS by clicking data and new data source then following the steps making sure to put sql CE when asked
if it works, you'll end up with an .sdf database
I provided a code snippet that fixed the issue on my related question here: Export SQL DataBase to WinForm DataSet and then to MDB Database using DataSet
I have created a desktop application with SQL Server 2008 as backend. I want to use this database from my application that is installed on a number of machines.
What are the requirements for that application to connect to the centralized database.?
It is pretty simple, You want the architecture as Client-Server model were the server has the database .Hence you need to have MS SQLserver 2005 or higher versions and create database connect it to sqlserver. Grant permission for the clients to access the database.
From visual studio side:
Add the above created .mdf(database file) as the new data source.
Data-->Add new Data Source , and follow the steps in the wizard[p.s the type of connection has to be sql sever type ]
while doing this a connection string will be created by VS. Use tht connection string to access from the client side.
This link would be useful : http://msdn.microsoft.com/en-us/library/sxds9ett(v=vs.80).aspx
To keep the connection string in its resources, ofcourse.
Resources are:
Doubleclick on project's Properties (at solution explorer).
Then Settings tab.
If there is no default setting file, create it by clicking the long link label.
Add a setting like "ConnectionString" with the value like "Data Source = ..." whatever.
Then you can run your sql scripts like:
SqlConnection conn =
new SqlConnection(Properties.Settings.Default.ConnectionString);
And go on.
I'm here for a trouble with SQL Server CE in a C# application.
This is a really simple question, at first I was trying to do an INSERT into a table, but it didn't do it, so I searched and the solution was to put the literal string to connect to the database.
try
{
cnTrupp.Open();
SqlCeCommand com = new SqlCeCommand("INSERT INTO tipo_venta(nombre) VALUES (#nombre)", cnTrupp);
com.Parameters.AddWithValue("#nombre", pNombre);
com.ExecuteNonQuery();
com.Dispose();
}
catch (SqlCeException e)
{
LogFile log = new LogFile(e.Message);
}
finally
{
cnTrupp.Close();
}
After that with the literal string, I was wondering, when I deploy the app, how I'm supposed to change that connection string? so it points to the actual database in the new computer
The comments on "Paul Sasik"'s post talk about the Data Source=|DataDirectory|\example.sdf entry in the app.config file of your application.
For the sake of completeness: This |DataDirectory| part is a macro that expands automatically to the folder where your application is running and should not be hardcoded. If you want to change the folder, you may use the following line in Program.cs:
AppDomain.CurrentDomain.SetData("DataDirectory", <New Folder>);
At least this is true for desktop applications. As mobile applications (in VS 2005 and 2008) don't support the same configuration mechanism, you have to create the connection string manually there.
Make use of the .NET app.config file. This is a VB article but will get you started.
.NET config files are fairly easy to work with but with information like a db connection, you might want to consider encrypting the string in the config file. Or at least the password. That is if security is a concern. Many times it's not. Especially on mobile devices which are inherently unsecure (at least in the WinCE world... up to CE5 v.6)