how to find connection string sql server via code not by properties - c#

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.

Related

I connected c# windows app with Access database (accdb) but the application doesn't work on other computers

I connected an Access database (accdb) with C#-windows application project.
The "accdb" database is located in a folder in desktop. It works correctly on my computer but when i build a setup file and installed it on other computer the software didn't work. (i know the problem is that the database located in the folder) but i dont't know how to change the code that after installation on other computer, it can still connect to the database.
Does anyone know how should i solve this problem?
Here is the simple connection that i wrote:
OleDbConnection con = new OleDbConnection(#"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\Users\aa\Test.accdb;Jet OLEDB:Database Password=123;");
It works correctly on my computer but when i build a setup file and installed it on other computer the software didn't work.
The primary reason for this is because that path doesn't exist on the other machine; you've hard-coded your path.
OleDbConnection con = new OleDbConnection(#"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\Users\aa\Test.accdb;Jet OLEDB:Database Password=123;");
C:\Users\aa\Test.accdb this is the actual issue, you shouldn't hard code this value, instead you have two options I can think of.
Look for the file along side the application where it is being executed from (this requires the file to be inside the same directory the exe is in).
You could allow the end user to enter the location of that file, if it exist, save this path to use again when needed.
You can use either or I mention above and or do both of them, your choice. Below is a simple example using option one above.
using System.Reflection;
using System.IO;
public static string GetDBConnection()
{
try
{
string dbExecPath = Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location), "Test.accdb");
return $"Provider=Microsoft.ACE.OLEDB.12.0;Data Source={ dbExecPath };Jet OLEDB:Database Password=123;";
}
catch (Exception)
{
return string.Empty;
}
}
This get's the assemblies location (path) and combines it with your file name (db file). Then combine's that with your other connection string parts and return's the whole connection string.
Please Note: the namespaces that have to be used and the db file must be in the same directory that the exe is if going this route.
Now you can call it like this:
OleDbConnection con = new OleDbConnection(GetDBConnection());
You may want to assign the GetDBConnection() to a var and check if it's empty before constructing your connection, it may be empty.

How to embed SQLite database files into WPF application

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

How to create dynamic database connection string C#

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)

How to create exe file with database in c# to run on client machine

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.

read a .db file in C#

string Path = #"c:\Database\Mydatabase.db";
string myConnectionString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + Path + ";Extended Properties=Paradox 5.x;";
// Define the database query
string mySelectQuery = "SELECT id,name FROM people WHERE id < 3;";
// Create a database connection object using the connection string
OleDbConnection myConnection = new OleDbConnection(myConnectionString);
// Create a database command on the connection using query
OleDbCommand myCommand = new OleDbCommand(mySelectQuery, myConnection);
// Open the connection
myCommand.Connection.Open();
// Create a database reader
OleDbDataReader myReader = myCommand.ExecuteReader(CommandBehavior.CloseConnection);
The Error is at myCommand.Connection.Open(); and it says:
'c:\Database\Mydatabase.db' is not a valid path. Make sure that the path name is spelled correctly and that you are connected to the server on which the file resides.
I am trying to read a .db file in C#. However, I am getting an error, I am sure that file is located there, the error does not make sense for me. Could you please help me ? Or How can I read a .db(paradox) database file in C# ?
EDIT:
string Path = #"c:\Database\";
The Error for this case is "The Microsoft Jet database engine could not find the object 'people'. Make sure the object exists and that you spell its name and the path name correctly."
If I change it like that, How can C# find which database file is gonna be used ? Since, I did not specify file name which is "Mydatabase.db" at anywhere
Confirmed it is an SQLite database, I just downloaded it on my phone and viewed it with an SQLite viewer.
You will need to download an ADO.NET provider for SQLite:
"Official" version (from SQLite, not MS)
http://system.data.sqlite.org/index.html/doc/trunk/www/index.wiki
Older version
http://sqlite.phxsoftware.com/
if the application cannot see the file than chances are it's a security issue. while "you" can access the file. the application cannot.
is this a web application? if so, then this is the problem. asp.net/IIS cannot see outside of its virtual directory. In which case you either need to elevate/modify privileges of the asp.net user account to access the file, or move the database file within the virtual directory. This is a good candidate for the App_Data directory.
Try one of these connection strings instead.
According to this site, you should only specify the folder name, not the db file.
Please note that you should only specify the folder where the database
resides. Not the database name itself.
The linked MSDN article says that Jet 4.0 Service Pack 5 should be used if you want to update the data, otherwise it may be read-only. In any case I would recommend installing the service pack.

Categories

Resources