I tried searching the net for this probably simple answer, but without success. I have my WPF app almost ready - using connection strings to connect to my 3 databases (EnteralDB, ParenteralDB, PatientDB) that have several tables.
Problem is that it works while debugging because I hard wired the connection string to specific location (my desktop)
using (SQLiteConnection con = new SQLiteConnection(#"Data Source= C:\Users\Peter\Desktop\EnteralDB"))
But how I can I make the connection string "universal" - meaning that it will work when I create setup for the app and it will install on a new computer? How to embed the database files into the project so they are PART of the project itself and then somehow point with the connection strings to them?
Thank you very much for help!
EDIT Actually, the comment by Clemens is correct. I changed the connection string to just the filename (EnteralDB.db), set copy if newer with content for the database properties and it is working
Related
I just created a desktop Winforms application with localhost database.
The connect string I am using is this:
SqlConnection connect = new SqlConnection(#"Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=C:\Users\Administrator\Desktop\learningsystem\LearningSystem\LearningSystem\LearningSystem.mdf;Integrated Security=True");
If I want to run my application on other computers, how should I make it work?
EDIT:SOLUTION
Thank for all the help! I tried the following steps. I think it is working now. But please correct me if I did something tricky.
1. add a new setting item in project property setting. App.config will automatically update:
<connectionStrings>
<add name="LearningSystem.Properties.Settings.LearningConn" connectionString="Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=|DataDirectory|\LearningSystem.mdf;Integrated Security=True;Connect Timeout=30"
providerName="System.Data.SqlClient" />
</connectionStrings>
2. In my program, just add the following statement to connect to the sql server
SqlConnection connect = new SqlConnection(#"Data Source = (LocalDB)\MSSQLLocalDB; AttachDbFilename=|DataDirectory|\LearningSystem.mdf;Integrated Security = True; Connect Timeout = 30");
Further question
If others will run this application on their computer(not in the same network), they just go into the project setting and change the value by selecting the database file I provide to them,the connectionString will automatically change, right?
Thanks!
It's generally a bad idea to hard code such stuff in your application. Normally, application settings and connection strings are placed in the application's configuration file (in the ConnectionStrings section).
Just like with all strings, you could build your connectionstring from dynamic parts (variables, settings, etc.) and then pass that generated connectionstring to the SqlConnection constructor. Again, to make those separate parts configurable without hard coding them in your application, you might want to add them to your application's configuration file (in the AppSettings section). But IMHO this is an overly complex solution in most scenarios. Putting the entire connectionstring in the ConnectionStrings section is more straightforward (and more flexible).
Anyway, again, to make your application configurable, you might use your application's configuration file (App.config or Web.config), you need to add a reference to System.Configuration in your project's .NET Framework dependencies and use the AppSettings and ConnectionStrings properties of the System.Configuration.ConfigurationManager class.
(Of course, there are more ways to make your application configurable. But using the application configuration file is one of the most straightforward solutions.)
Edit:
When deploying your app to another computer, you need to copy its database over too. If you want to use the application on multiple machines and let them connect to the same database, you might want to leave LocalDB and migrate the data to a SQL Server (Express) instance and make it accessible over the (local) network.
Edit 2 (regarding the recent edits in your post):
I see in step 1 that you are using an application setting (called LearningConn) in your solution now. That's fine. However, it is important that you also use that setting in step 2, like this:
SqlConnection connect = new SqlConnection(Properties.Settings.Default.LearningConn);
If you change the setting in Visual Studio, it will update the connection string. Since the setting will probably have application scope, it will not be possible to update the setting/connection string within your application in runtime (by the user).
I'm not sure if your connection string using |DataDirectory| will always work as expected in all scenarios. I have only been using it in ASP.NET webapplications. If it does work in WinForms applications, you might read this document to learn how to set it up. But personally I am somewhat sceptical about this approach.
I personally would opt for a solution where you use a placeholder in your connection string, which you replace with the full path to the .mdf file before you pass it to your SqlConnection constructor.
When you use "{DBFILE}" as the placeholder, for example, the value of your LearningConn setting would look like this:
Data
Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename={DBFILE};Integrated
Security=True;Connect Timeout=30
(Note that this value should be a single line without any line breaks!)
You might create a separate setting in your application called DbFile (of type string) to store the actual value that should be put in place of {DBFILE} in your connection string. When you use scope "user" for that setting, the value might be changed from within the application by the user. When saved, it might not be saved directly in the application's configuration file, however, but in an additional configuration file hidden somewhere in the user's Windows user profile. You might read this document to learn more about application settings.
Your code in step 2 might eventually look something like this:
string connectString = Properties.Settings.Default.LearningConn;
string dbFile = Properties.Settings.Default.LearningSystemDb;
connectString = connectString.Replace("{DBFILE}", dbFile);
SqlConnection connect = new SqlConnection(connectString);
To let your application's users select and store the database .mdf file to use, you might include (a variation of) the following code in your application somewhere:
using (var dlg = new System.Windows.Forms.OpenFileDialog())
{
dlg.Title = "Select database file to use";
dlg.Filter = "Database Files (*.mdf)|*.mdf";
dlg.CheckFileExists = true;
if (dlg.ShowDialog() == System.Windows.Forms.DialogResult.OK)
{
Properties.Settings.Default.DbFile = dlg.FileName;
Properties.Settings.Default.Save();
}
}
Your question is not clear!
you need work with one Database on 2 or more PC?!
OR
you need work with 2 separate programs?
if you need 2 separate programs :
you must copy .mdf file to other PC at same address or keep mdf address in app.config and read it before connect to SQL.
How to Read From app.config
if you need work with one Db you must connect to dataBase Server such as SQL Server and keep connection string in app.config in connectionStrings tag.
Get connection string from App.config
If you want to work on other PCs, rather than building it dynamically make the connection string more generic:
Server=(localdb)\\mssqllocaldb;Database=LearningSystem;Trusted_Connection=True;MultipleActiveResultSets=true
This should create the mdf file under 'mssqllocaldb' in %appdata% for each user. You might need LocalDb installed (which you tick during SQL Server installation)
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.
Can someone help me out?
Whenever I switch computers I have to copy the connection string again. I don't want to do that. Is there any alternative method for finding it? I am using Visual Studio 2013 and C#.
I have kept the application in a flash drive so I may use it on any computer. But it only works on my computer.
con = new SqlConnection(#"Data Source=(LocalDB)\v11.0;AttachDbFilename=H:\DataBaseApp\DataBaseApp\DB.mdf;Integrated Security=True");
con.Open();
This is what I'm using but I would appreciate if someone tells me how not to use this.
1) Create connection string property
2) Add connection string to web config. DataSource should be some alias like TestDataBase.
3) Fill the connection string property from web config value.
4) Add Sql Alias on the current PC with name TestDataBase.
When you go to another PC you should only configure new SQL Alias.
In this case multiple users can work without changes in the code(Example source control).
You can save your connection string in any text file, for example: conn.txt and put it in bin\Debug folder. Now, you can read it at runtime by using this code.
string path = Path.Combine(Application.StartupPath, "conn.txt");
string connStrg = System.IO.File.ReadAllText(path);
using (SqlConnection cnn = new SqlConnection(connStrg))
{
...
}
When you publish your application you need to just create that file where the application is installed. I mean if your application is installed in any specific drive like D:\\MyFolder\\MyApp.exe then your conn.txt file should be created on D:\\MyFolder.
I am creating a C# windows form application, the working can be summarized as users fills some form and data is saved in SQL database. Now the problem I am facing is that I have to deliver this as an executable file to someone. But the problem is database is creating issues as the connection string is not match with that computer. I know that if a distribute projects I can put connection string in app.config and every user can change it according to his/her machine. But i want to make it more convenient for the user not to change the connection string as i am only giving the executable file to client. as i have the connection string in my project is
String ConString = #"Data Source=(LocalDB)\v11.0; AttachDbFilename=D:\Users\khan\Desktop\MyApp\MyApp\Database1.mdf;Integrated Security=True";
So how to make it generic so that the client does not need to change the connections string. Kindly elp me out in this issue.I have searched a lot but still not done with it.
Try to use a Enviroment Variable instead of a fixed path in AttachDbFilename.
For example %APPDATA%\Database1.mdf.
I am having issues connecting to my sqlite database. The file is located in the application's folder. Here is the connection string
string path = "Data Source=MY.db";
I can get it to work if I use the absolute path, but it gives me a "table not found" error if I try to use a relative path. Any ideas?
You are opening up a different -- perhaps a new -- database that does not have said table. (Yes, SQLite will happily create a new database with the default connection settings.)
Make sure the correct database is opened. Remember, relative path is relative to the Current Working Directory, which is likely not that which is expected.
(The working directory is influenced from where, and how, the process is loaded. The working directory for a "Debug" session can be set under Project Settings / Debug / Start Options, for instance.)
Happy coding.
See also:
Make SQLite connection fail if database is missing? (deleted/moved)
Defining a working directory for executing a program (C#) (Shows how to set the current working directory to the directory containing the executing assembly.)
How do I get/set a winforms application's working directory?
Getting path relative to the current working directory?
This happened when you haven't saved the database and its table while using GUI Manager for SQLite .
Two solution;
1) Save your database and its table with CTR+S in GUI Manager
2) Or Simply Just close your GUI manager of SQlite and save all .
Important ! I am using GUI manger for SQLITE (DB Browser for SQLITE) and its all about that.
I've had the same problem for both my windows application (C#) and web application (ASP.net). I usually use SQLite because I found it more easier, especially when I worked with connection strings. But the main obstacle for me was to put a relative path in my code, so I can publish it without worrying about being unable to find the database. I've tried many things(using "|Data Directory|", "~/", "./", ...), and none of them works until I found these solutions. It seems the code is working for me, but wonder if I'm using them right?!
Web Application:
SQLiteConnection sql_con = new SQLiteConnection("Data Source =" + Server.MapPath("~/") + "mydb.db; Version = 3; New = false;);
Windows App:
SQLiteConnection sql_con = new SQLiteConnection("Data Source =" + System.IO.Path.GetDirectoryName(Application.ExecutablePath) + "mydb.db; Version = 3; New = false; Read Only = true");
just replace your .database file into \bin\Debug in project folder, because in your case compiler creates DB file with same name but its totally empty 0bytes