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
Related
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.
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
I am creating a plugin for AutoCAD which uses an external Database(SQLite).
and on rare occasions i am getting the "table not found" error. Its driving me crazy. I have seen plenty of forums for answers could not find a solution.
it is working on most cases only few instances it throwing this error.
How do I solve this issue.
I am using relative path to the DB and it lies within the Debug/ release folder.
What is the best approach to attach a db to a application (in my case its a .dll not exe)
thanks guys for reply...Sorry I didnt get any email notification...
Here is the information you requested.
I have a seperate class-which handles connections.
here is how i I connect to the DB.
public static SQLiteConnection GetConnection()
{
string conn_string = string.Format("Data Source=./sdf_db1.s3db");
SQLiteConnection conn = new SQLiteConnection(conn_string);
if (!System.IO.File.Exists("./sdf_db1.s3db"))
{
Global.variables.mess_out_exception("Missing Database file", "Error");
}
return conn;
}
Since this is a plugin for AutoCAD Civil3D it resides in the Appdata\autodesk folder to load on start-up. Everything about the app is working great except rarely I get the table not found error..looks like may be the relative path cannot resolve quickly when the application is started.
I have difficulty finding the absolute path if I tried to use "Application.ExecutablePath;" and few other things which I find online..all I get is the location of Acad.exe not the location of the plugin.
How do I get the absolute path of the location of the plugin to get the location of the DB(since the DB and .dll lies in the same folder).
How do I use both absolute and relative path in the connection string (so if the relative path fails the code can try to locate the db using the absolute path).
Any other suggestion would be great. Thanks
I Found the cause for the issue,
When I run the application and close the application correctly (Means after completing all the process) it works fine I dont get any error message...
I get the error only when I close the window of the application in between. Looks like the connection opened for the DB is still busy if I try to run the application.
Get the path of the plugin with
var asmpath = Path.GetDirectoryName( Assembly.GetExecutingAssembly().Location );
Why not take an alternate route?
Instead of trying to find your DLL and associated SQLite database, I would recommend that you install them in a specific location. This way you can easily package it with an installer.
You can utilize automatic loading of .NET modules through AutoCAD with registry keys:
http://through-the-interface.typepad.com/through_the_interface/2006/09/automatic_loadi.html
With this, you can simply install your AutoCAD plugins as if they were a normal program, and get AutoCAD to load them for you on launch.
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.
I used the PostBuildevnt script to launch the application form link
http://blogs.msdn.com/b/astebner/archive/2006/08/12/696833.aspx?wa=wsignin1.0&CommentPosted=true
and launching the app successfully.I am using the sqllite for app.
I added the DB file in Application Folder/DataBase and using the following code to open the Db file.
string ConnectionString = "data source=" + Path.GetFullPath(".") + "\\DataBase\\CATTDB.db";
If i launch the app from the installation wizard,it is not connecting to db file.it is throwing the error like "Unable to open the file".
If i launch from the start menu or desktop icon ,it is working fine..
What is the problem here?
please help me..
It could be that your working directoy is different when started from the installer...
What does Path.GetFullPath(".") return in this case (log and/or display the value)?
There is always the issue of permission/rights - depending on your OS (i.e. Windows 7...) and the user your running the app with (i.a. Administrator?) for security reasons you are not allowed to write in the application directory... if you need someplace with read+write you should use http://msdn.microsoft.com/de-de/library/system.windows.forms.application.userappdatapath.aspx
Just check whether the db is in that path -if not copy it there- and use it there...
Other locations could be ApplicationData/CommonApplicationData/LocalApplicationData from http://msdn.microsoft.com/de-de/library/14tx8hby.aspx and http://msdn.microsoft.com/de-de/library/system.environment.specialfolder.aspx
All the files are copying correctly..
I tried with Application.ExecutablePath instead of Path.GetFullPath(".")
it work's great...