Local database, I need some examples - c#

I'm making an app that will be installed and run on multiple computers, my target is to make an empty local database file that is installed with the app and when user uses the app his database to be filled with the data from the app .
can you provide me with the following examples :
what do I need to do so my app can connect to its local database
how to execute a query with variables from the app for example how would you add to the database the following thing
String abc = "ABC";
String BBB = "Something longer than abc";
and etc
Edit ::
I am using a "local database" created from " add > new item > Local database" so how would i connect to that ? Sorry for the dumb question .. i have never used databases in .net

Depending on the needs you could also consider Sql CE. I'm sure that if you specified the database you're thinking of using, or your requirements if you're usure you would get proper and real examples of connection strings etc.
Edit: Here's code for SqlCe / Sql Compact
public void ConnectListAndSaveSQLCompactExample()
{
// Create a connection to the file datafile.sdf in the program folder
string dbfile = new System.IO.FileInfo(System.Reflection.Assembly.GetExecutingAssembly().Location).DirectoryName + "\\datafile.sdf";
SqlCeConnection connection = new SqlCeConnection("datasource=" + dbfile);
// Read all rows from the table test_table into a dataset (note, the adapter automatically opens the connection)
SqlCeDataAdapter adapter = new SqlCeDataAdapter("select * from test_table", connection);
DataSet data = new DataSet();
adapter.Fill(data);
// Add a row to the test_table (assume that table consists of a text column)
data.Tables[0].Rows.Add(new object[] { "New row added by code" });
// Save data back to the databasefile
adapter.Update(data);
// Close
connection.Close();
}
Remember to add a reference to System.Data.SqlServerCe

I'm not seeing anybody suggesting SQL Compact; it's similar to SQLite in that it doesn't require installation and tailors to the low-end database. It grew out of SQL Mobile and as such has a small footprint and limited feature-set, but if you're familiar with Microsoft's SQL offerings it should have some familiarity.
SQL Express is another option, but be aware that it requires a standalone installation and is a bit beefier than you might need for an applciation's local cache. That said it's also quite a bit more powerful than SQL Compact or SQLite.

Seems like you're:
-Making a C# app that will be installed and run on multiple
computers
-That needs a local database (I'm assuming an RDBMS)
-You need to generate a blank database at installation
-You then need to be able to connect to the database and populate it when
the app runs.
In general, it seems that you need to read up on using a small database engine for applications. I'd start by checking out SQLite, especially if you need multi-OS capability (eg., your C# program will run on Microsoft's .NET Framework and Novell's Mono). There are C# wrappers for accessing the SQLite database.

I believe this question is about the "Local Database" item template in Visual Studio:

What are you considering as a database? From what little you've provided in your question, I'd suggest SQLite.
You can get sample code from their site Sqlite.NET

Not sure I fully understand what you're asking but Sqlite is a good option for lightweight, locally deployed database persistence. Have a look here:
http://www.sqlite.org/
and here for an ADO.NET provider..
http://sqlite.phxsoftware.com/

For 1)
The easiest way to provide this functionality is through SQL Server Express User Instances. SQL Server Express is free, so your user does not have to pay additional license for SQL Server, and the User Instance is file-based, which suits your requirement.
For 2)
This is a big topic. You may want to go through some of the tutorials from Microsoft to get the feeling of how to connect to DB, etc.

Related

ASP.NET MVC C# change code from accessing a mySQL database to a MSSQL database

I have an application that I used to connect to a mySQL database. I have installed the MySQL.Data package and I use this code to build my connection:
services.AddScoped<System.Data.IDbConnection>((s) =>
{
IDbConnection conn = new MySqlConnection(Configuration.GetConnectionString("databasename"));
conn.Open();
return conn;
});
This works fine as I am able to read/write data from the database.
Now, I need to have the same application access a MS SQL database. The tables are all the same and the fields on each table are the same as well. I am having a hard time finding what I should change my code to (or what package I should include). When I remove the MySQL.Data package, the MySqlConnection function becomes invalid (as would be expected).
Any idea what package to include and what function to use to establish the connection?
Any assistance is greatly appreciated.
Thank you!
EDIT #1
I found an old stackoverflow post (I should have referenced it here but I closed the window) that talks about this very issue. The suggestion was to add
using System.Data.SqlClient;
and then change the assignment code to
IDbConnection conn = new SqlConnection(Configuration.GetConnectionString("databasename"));
I made these changes and now I get this error within the code:
Im at a loss as to how to resolve this. I verified that my project is in framework .NET core 3.1
Not sure about size of your project and detailed requirements but I would suggest to use libraries like:
Entity Framework - no SQL knowledge needed, can connect to any Db technology, almost no code changes required when switching between Db providers
or
Dapper - fast lightweight also supports multiple Db providers but you need to write correct SQL commands yourself specific for each Db technology you use

MySQL c# Winform - Create new database from dump file (localhost)

I have a problem I need to solve, but not know how exactly. I have a WinForms application (C#) which connects to an online MySQL server - no problem there. In this application I have an option to make database backups (basically I dump this database to a local file on a computer).
I would like to locally "open" this backup on client's computer (to check some old data) - I don't want to make database restore on my server, because database must still be in use for other users. I want to make clean install of MySQL on a local computer and connect to it trough localhost (like I do for testing ), but I do not have physical access to that computer. I can send MySQL installer to my client, but how to go about automatically creating user with password and database from my dump file?
I know how to create a new database if it doesn't exist, but how to do it if it's clean install of MySQL server - no user and password yet.
string connStr = "server=localhost;user=root;port=3306;password=????;";
using (var conn = new MySqlConnection(connStr))
using (var cmd = conn.CreateCommand())
{
conn.Open();
cmd.CommandText = "CREATE DATABASE IF NOT EXISTS `hello`;";
cmd.ExecuteNonQuery();
}
Any help and direction is appreciated.
Regards!
I don't know whether I understand your problem. However,if you install a new Mysql,you can use root user through no database.
Anyway, one thing you need to know,Connect database must has user and password for mysql or sqlserver.
You may need to be more concise description of your problem.

Local DB in Visual Studio 2015

After a few years, I have returned to writing in C# and I am really struggling here - I would like to have my app to have a local SQL database. I have added Service-based database and "Database1.mdf" was added to my project. I created a table and added some data just to see if it is working but I cannot connect to it. I tried numerous connection strings with no success (Server not accessible).
Do I need to run something else in the background? I thought that I might have a local database and with .NET client I can access it, and I hoped it would work whenever I bring my application (also not requiring any SQL server running). Is that wrong?
If you don't require any SQL server, take a look at SQLite. This is lite SQL database engine. Database is just one file. C# has a great library to SQLite on NuGet: https://www.nuget.org/profiles/mistachkin
SQLite is widely used, event in Android (as a native db engine).
here is what i use to connect. it appears as a Data Connection in Server Explorer.
string con2 = #"Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=" + Application.StartupPath + "\\jobfile_2017.mdf;Integrated Security=True;Connect Timeout=30";
when i first started working with these, i used this source 1
it works on PC's that i have nothing installed (not even office) but as i said i'd be interested to know of any shortcomings of this method
I experiencing same problem and decided to move mdf file to static c:\db directory. Connection string was changed to incorporate new file location (AttachDbFile).
But AttachDbFile has some issues also (by some reason one table in db is inaccesible and error is access denied).
So I decided to move to Sqlite. LocalDb has many issues to work with. I read good note to resolve problem: in command line stop/remove/start name of instance. But it nuissance.
Wish you good luck to work with these db files.

Firebird 1.5 / Asp net VS 2010 (legacy database .CDB extension)

I have an old system which generated me a database in .CDB extension (i run on Firebird-1.5.6.5026-0-Win32) and i can access this database in IBExpert to query and stuff. But i need to write an application in .NET (VS 2010 4.0 framaework) so i can read this database and access some of the data to insert into a table inside SQLServer.
I tried many things, changed the server version and other things but i now all i get is ''Cannot find fbembed.dll'' exception error while trying to open the connection. My FB server doesnt have this file since he uses the 'fbclient.dll' already.
Any thoughts on how to connect my application to this .CDB database?
(this firebird version is the same that the legacy system is running, so i used the 1.7RC firebird .net provider within this server)
The connection string used is:
<add name="FirebirdConnectionString" connectionString="User=SYSDBA;Password=masterkey;
Database=localhost:C:\temp\BD\E‌​CLECTIC.CDB;DataSource=localhost;Port=3051;
Dialect=3;Charset=NONE;Role=;Connectio‌​n lifetime=15; Pooling=false;
MinPoolSize=0; MaxPoolSize=50; Packet Size=8192; ServerType=1;"
providerName="FirebirdSql.Data.FirebirdClient"/>
Unless you really want to use Firebird embedded (which you don't as you also specify localhost), you should not specify ServerType=1, but either leave it out entirely or set ServerType=0.
As to your other problem you mention in the comments, I suggest you check if this solves it and otherwise create a new question with more information.

Connecting to a database from the beginning

I have been working in a business writing advanced software apps, and obviously im provided with access to our SQL server and all the connection strings needed.This is fine for my job now - but what if i wanted to do this for a new (very small) business... If i wanted to purchase a small database server and set up a piece of software that talks to the databases on this server, how would i go about a) Talking and connecting to the server in code (c#) and b)What would i need regarding things like internet/phone connections etc to make this possible.
Edit: the reason it would need a server is because it would need to be accessed from 2 or 3 different computers in different locations?
Actually there are quite a few ways to create a database connection, but I would say one of the easiest ways is to utilize the methods and classes found in System.Data.SQLClient. A basic connection would look something like the following:
using System.Data.SQLClient;
namespace YourNamespace
{
public class DatabaseConnect
{
public DataType getData()
{
DataType dataObj = new DataType();
SqlConnection testConn = new SqlConnection("connection string here");
SqlCommand testCommand = new SqlCommand("select * from dataTable", testConn);
testConn.Open()
using (SqlDataReader reader = testCommand.ExecuteReader())
{
while (reader.Read())
{
//Get data from reader and set into DataType object
}
}
return dataObj;
}
}
}
Keep in mind, this is a very, very simple version of a connection for reading data, but it should give you an idea of what you need to do. Make sure to use a "using" or "try/catch" statement to ensure that the connection is closed and resources are freed after each use (whether it successfully gets data or not).
As for your other question about what equipment you may require. In the beginning I would suggest just creating the database on your local machine and running tests from there. Once you are confident with trading data back and forth, feel free to move the database to another box or an online server. Any internet connection type should suffice, though I can't vouch for dial-up, haven't used it in years.
One final note, if you do happen to decide to move to an online server system, make sure that the service you use allows for outside connections. Certain services use shared server systems, and force users to use their internal database interfaces to manage and write to the database.
--- EDIT ---
As for the server system itself, build up a separate box on your local network that you can see, and load up the database software of your choice. Since you are using C#, it would probably be easiest to go with Microsoft SQL Server 2005 / 2008. The installation is rather straightforward, and it will prompt you to automatically create your first database while installing.
After installation it will be up to you to add in the tables, stored procedures, custom functions, etc... Once your base structure is created, go ahead and use the above code to make some simple connections. Since you are familiar with the above practices then I'm sure you know that all you really need to do is target the server machine and database in the connection string to be on your way.
In case your application is small (by small I mean the usage of resources like CPU and memory) then your SQL Server can reside on the same box.
Else you need to have a separate server box for your database and connect to that from your application. In this case, preferably your database box and application box would be on the local area network.
Check this link for having a connection to SQL Server from C# code - http://www.codeproject.com/KB/database/sql_in_csharp.aspx
cheers
You should probably expose your database with an xml web services layer, so that your architecture will be scalable. The general idea is host your sql server and webservices, using Native SQL Server XML Web Services you can make this available to your remote clients. When in your clients you simply add a service reference in Visual Studio and your data will now be available in your client app.
Hope this helps some.
Cheers
You may find the connectionstrings website useful - worth bookmarking.

Categories

Resources