I have a folder 'Data' in my WPF application in which there is an .sdf database file.
This file is the database for my application.
When developing my app I used a fixed path to my db like this:
'Data Source=P:\Dropbox\Projects\MembersApp\MembersApp\bin\Debug\Data\RF_db.sdf'
Now I want to use the |DataDirectory| value so that the app always can find the db, were ever the app is installed. I found this solution on StackOverflow:
string executable = System.Reflection.Assembly.GetExecutingAssembly().Location;
string path = (System.IO.Path.GetDirectoryName(executable));
AppDomain.CurrentDomain.SetData("DataDirectory", path);
string dataSourceHome = "Data Source=|DataDirectory|\RF_db.sdf";
But is giving me an error on the last line 'Bad compile constant value'. I've tried with:
string dataSourceHome = #"Data Source=|DataDirectory|\RF_db.sdf";
But that doesn't work.
Any idea what's wrong here?
Do not change DataDirectory in your code; it is set by the installer and changing it will prevent your app from knowing where the data was installed. Just use:
string dataSourceHome = #"Data Source=|DataDirectory|\RF_db.sdf";
And nothing else. Do not call AppDomain.CurrentDomain.SetData("DataDirectory", path); that's what is breaking things.
You could use:
string dataSourceHome = string.Format("Data Source={0}\\RF_db.sdf", Environment.CurrentDirectory);
or
string dataSourceHome = string.Format("Data Source={0}\\RF_db.sdf", System.IO.Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location));
It looks like your creating a ADO.Net connection string. Isn't there just information missing from your dataSourceHome?
Have a look at this post.
Or a different approach to creating the connection might be found on ConnectionStrings.com.
Related
I am creating an application which uses access file from shared network.The application works fine when the access file is placed local.But when I placed it in shared path and trying to connect.It is throwing an exception."An OLE DB Provider was not specified in the ConnectionString. 'Provider=SQLOLEDB
Here is my code:
string connectionString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=\\server\\MyFirstProject\\SampleDB2.accdb";
using (OleDbConnection con = new OleDbConnection(connectionString))
{
string command = "INSERT INTO emp_status(emp_id,hours,feeded_on,comments)";
command += "VALUES(#emp_id,#hours,#feeded_on,#comments)";
Could anyone help me how to resolve this issue and Am I missing something?
I am using OLEB as a datasourse and Access 2013
Any Suggestions or explanations would definitely helps me.
Thanks in advance!!
You need to escape the leading double slash as well...
string connectionString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=\\\\server\\MyFirstProject\\SampleDB2.accdb";
I haven't got anything to check this on here, but I'm fairly sure this is your answer. Also, watch out for reserved words, E.g. "hours" might be one in which case it should be [hours].
Also, you haven't specifically included adding the parameter values in your question. I assume you are doing it but if not then see my coding example here...
VB 2010 error (INSERT INTO) syntax error
I'm working on an app linked to a local db and I'd like to get the path of db dynamically. I don't know where exactly users will copy this app, so I'd like to get the path to the db automatically. I wrote the following code, it gets the path, but not exactly. I mean, if I have my app in: C:\Users\ROG\Desktop , it says that there is no db in C:\Users\ROG . So it doesn't get the last location of it. Why is that and how to solve it?
I connect to it as follow:
var connString = (#"Data Source=" +
Directory.GetParent(Directory.GetCurrentDirectory()).Parent.FullName +
#"\Angajati.sdf");
Consider using the following code to determine appllication base directory:
AppDomain.CurrentDomain.BaseDirectory
Full code will look like the following:
var connString = "Data Source=" +
System.IO.Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Angajati.sdf");
try to use the following code
var connString = (#"Data Source=" +
System.IO.Path.Combine(System.IO.Path.GetDirectoryName(
System.Reflection.Assembly.GetExecutingAssembly().Location),
"Angajati.sdf"));
Rather than using get current directory I suggest using Application Path. That's because if an OpenFileDialog be used the current directory changes but the applicationPath is the same.
System.Reflection.Assembly.GetExecutingAssembly().Location
I hope it would be helpful.
This is the 1st time I am using C# connection with db, also I dont use access.
I just want to know the initial steps required to connect the access db to visual studio C# windows application.
I have searched though the internet, It helped a lot. I cant find my mistake in the code. I think I am missing some steps in establishing the connection with the db.
here is the error that appears when I try to run the program "'\f38910\Users\kainat.baig\Desktop\AAA\Database101' 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."
CODE:
OleDbConnection bookConn;
OleDbCommand oleDbCmd = new OleDbCommand();
String connParam = #"Provider=Microsoft.Jet.OLEDB.4.0;Data Source= \\f38910\Users\kainat.baig\Desktop\AAA\Database101; Persist Security Info=False";
public Form1()
{
bookConn = new OleDbConnection(connParam);
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
bookConn.Open(); //*ERROR LINE
oleDbCmd.Connection = bookConn;
bookConn.Close();
}
First your file name does not have the file extension name like .mdb
Database101\MyDB.mdb
Second, if it is in a network. Would it be better if you net use first in you DOS prompt to assign a drive letter for your network, like:
net use z: \\f38910\Users\kainat.baig\Desktop\AAA\Database101 your_password /USER:your_account
Then your connection string will be shorter then:
String connParam = #"Provider=Microsoft.Jet.OLEDB.4.0;Data Source= z:\MyDB.mdb; Persist Security Info=False";
If the file extension by the way is .accdb instead of .mdb it should be:
String connParam = #"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=z:\MyDB.mdb;;Persist Security Info=False;"
Or simply your path is simply wrong.
Go to windows explorer and just clink on the path where your file is and copy paste it.
You forget to add .mdb after database name or .accdb if you are using Microsoft Office Access 2007 or higher database but, for that you have to change Provider also.
String connParam = #"Provider=Microsoft.Jet.OLEDB.4.0;Data Source= \\f38910\Users\kainat.baig\Desktop\AAA\Database101.mdb; Persist Security Info=False";
Or you can use connection string like this
String connParam = #"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=\\f38910\Users\kainat.baig\Desktop\AAA\Database101.mdb;User Id=admin;Password=;"
EDITED:
for ACCESS 2010
#"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=\\f38910\Users\kainat.baig\Desktop\AAA\Database101.accdb"
I am doing a SETUP project for a C# winforms, sqlite application.
Connection string seems to a bit of a problem. The user will put the Database he wants to work with at a location(which v will tell him). In this example it is "C:\\Program Files(x86)\\DefaultCompany\\RSetup"; The user can work his own copy of the DB.
So I am setting the data directory to this path in the Program.cs Main
This is the only way I can think of. If there is a better way thats grt!!.
App.config
<add name="ConnString" connectionString="|DataDirectory|\MySQlite.db;Compress=True;Version=3"
providerName="System.Data.Sqlite" />
Program.cs
Setting the datadirectory to the path of the executable. Currently hard coded the path of the executable
static void Main()
{
AppDomain.CurrentDomain.SetData("DataDirectory","C:\\Program Files(x86)\\DefaultCompany\\RSetup");
This doesn't seem to be working. It doesn't give any error except the data is not blank. Doesn't seem to be working in both set up and the regular project
Thank you
JC
You could ask the user where the database is located, store that path somewhere (such as User Settings) and then you can retrieve it at any time. This would give the user more flexibility of where to put it and multiple users on the same machine could have their own database if desired.
Here is some pseudocode...
string dbLocation = Properties.Settings.Default.DatabaseLocation;
if (string.IsNullOrWhiteSpace(dbLocation)
{
dbLocation = AskUserForLocation();
Properties.Settings.Default.DatabaseLocation = dbLocation;
Properties.Settings.Default.Save();
}
AppDomain.CurrentDomain.SetData("DataDirectory",dbLocation);
Using this approach you could also add a menu option to allow the user to change the location if desired.
It also gives you the ability to retrieve the value anywhere, including where you create a connection, you can append the path to the location between where you read the connection string and you create a new connection.
SQLiteConnection myConnection = new SQLiteConnection;();
myConnection.ConnectionString = Path.Combine(Properties.Settings.Default.DatabaseLocation, myConnectionString);
myConnection.Open();
I am going off of this tutorial: http://www.dotnetperls.com/sqlclient . Instead of adding a data source and a having visual studio compile my connecting string - I want to do it myself. The reason being is that the database will not always be the same and I want this application to be able to use different databases depending on which I point it to.
So how can I manually create the connection string? I am using SQL Server 2005.
Step 1: Go to connectionstrings.com and find the proper format for your database.
Step 2: Plug in the appropriate values to the connection string.
Step 3: Pass that string to the constructor of SqlConnection.
I would also suggest storing your connection string in your app.config/web.config file. You can then modify them easily if needed. The proper format can be found at MSDN - connectionStrings element. You then change your code to:
SqlConnection sqlConn = new SqlConnection(
ConfigurationManager.ConnectionStrings["ConnStringName"].ConnectionString);
I don't see where the connection string is "compiled".
In the code
SqlConnection con = new SqlConnection(
ConsoleApplication1.Properties.Settings.Default.masterConnectionString)
ConsoleApplication1.Properties.Settings.Default.masterConnectionString is a field and it can be replaced with any other appropriate string.
for SQL Server format of the connection string is
"Data Source = server_address; Initial Catalog = database_name; User ID = UserId; Password = **;"
save this connection string in a string variable and use with connection object.
either way you can add in web.config file.
<ConnectionString>
<add name = "name_of_connecctionString" ConnectionString = "Data Source = server_address; Initial Catalog = database_name; User ID = UserId; Password = ****;" ProviderName = "system.Data.SqlClient"/>
</ConnectionString>
you can change the provider as needed by you.
then in code behind file access this particular connection string using configuration manager.