SQLiteException: 'unable to open database file' - c#

As shown in pictures, "ProjectDB.db" is a database I built through the SQLite Compact Toolbox. The database indeed exists in that folder path. The exception as in the title is thrown as I debug the app.
UWP App. Visual Studio 2017. Windows 10.
Snapshot of Errors while running application
enter image description here
enter image description here
Connection string for connecting SQL lite Database
SQLiteConnection db =
new SQLiteConnection(#"Data Source=C:\Users\georg\source\repos\DatabasePractice\ProjectDB.db;Version=3;";
db.Open();

Sqlite on Windows a directory/path should use a double backslash like this:
C:\\Users\\georg\\source
If this does not solve your problem, attempt these troubleshooting steps:
Is the Database stored on a remote server or 'read-only' directory?
Is the parent directory a 'read-only' directory?
Try executing your code with the Source="...Practice\ProjectDB;" not "\ProjectDB.db;"
Is something else attempting to read the database? Although this should throw a 'database locked' exception which makes this one unlikely.

I was facing same issue on the shared hosting server, My C# code was able to read data from SQLIte db file. But while add / update data it was throwing Error "unable to open database"
I tried many options suggested on stackoverflow But after referring https://stackoverflow.com/a/17780808/2021073 and
https://www.sqlite.org/pragma.html#pragma_journal_mode I tried adding journal mode=Off; to the Connection string
and it worked for me
sample code
SQLiteConnection connection = new SQLiteConnection("Data Source=G:\dbfolder\sqlite3.db;Version=3;Mode=ReadWrite;journal mode=Off;", true);

Related

How do I create a generic file path to a local database in a C# Application?

I have a simple data entry Windows Form with a datagridview display that links to a local database. When I run the program and try to add data on another computer, I get this message:
Unhandled exception has occurred in your application. If you click Continue, the application will ignore this error and attempt to continue. If you click Quit, the application will close immediately.
An attempt to attach an auto-named database for file C:\Users\roberto.yepez\Documents\Visual Studio\2010\Projects\Financial Aid Calculator\Financial Aid Calculator\StudentInfo1.mdf failed. A database with the same name exists, or specified file cannot be opened, or it is located on UNC share."
The file path is to the path on the computer where I coded the program.
Here is my code:
SqlConnection conn = new SqlConnection(#"Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename='C:\Users\roberto.yepez\Documents\Visual Studio 2010\Projects\Financial Aid Calculator\Financial Aid Calculator\StudentInfo1.mdf';Integrated Security=True".ToString());
I am a self-taught coder, please help! :)
I believe you're running into a problem because your local sql server to which your code is trying to attach the StudentInfo1.mdf (whose path is in the connection string) already contains a database called StudentInfo1 - it decided to try and create a database of this name based on the name of the mdf file. I'm guessing that you can pick your own name by specifying Initial Catalog in your connection string but this would mean there are two databases with possibly the same set of tables and a potential for confusion
Per the comment I posted I would instead advocate that you use SQL Server Management Studio to permanently attach your db (you make have already done this) and then adjust your connection string so that it refers to the permanently attached db. This reduces the chances that your next question will be "my code says it's updating my db but I cannot see any changes!?"
Please move this connection string
"Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename='C:\Users\roberto.yepez\Documents\Visual Studio 2010\Projects\Financial Aid Calculator\Financial Aid Calculator\StudentInfo1.mdf';Integrated Security=True"
to app.config file. When you deploy to production, change the paths in that app.config, according to the production machine settings.
You can even apply transformations on the app.config to deploy in various machines/scenarios.

c# SQL) unable to open physical file(MS localdb .mdf) after attaching the .mdf file which was created in another computer(server)

I'm developing Windows Desktop appication(C# WPF) with Microsoft localdb(.mdf) and I want that users of my software can carry their localdb (.mdf) file when they move to other places(computers). The localdb (.mdf) file is created on the first computer.
To test my application, I copied my localdb file from computer A to computer B and attached with below code successfully.
string attach_greendbnameQuery = string.Format(#"EXEC sp_attach_db #dbname = N'greendb_{0}', #filename1 = N'{1}\greendb_{0}.mdf'", textBoxGreenLogin.Text, Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData).ToString());
SqlCommand attach_greendbnamecomm = new SqlCommand(attach_greendbnameQuery, check_datadbinmasterConn);
attach_greendbnamecomm.ExecuteNonQuery();
And I could read and write data into the moved localdb file.
However, when I run backup command on this database, exception occurs like,
'Unable to open physical file, Operating system error 32, process cannot open the file because the file is in use by another process'
If I enter Server Management Studio- Security-KayLee-PC\KayLee- User Mapping,
the users of all other localdb are 'dbo' but only the user of manually moved database is KayLee-PC\KayLee and only 'public' is checked and all other database roles are not checked including db_owner. (I always start(login) Windows(O/S) with KayLee-PC\Kaylee account)
I tried to make all roles checked to database roles even to server roles but failed.
Even, I tried to drop the user KayLee-PC\KayLee through below code but the exception message show as,
'User 'KayLee-PC\KayLee' does not exist in current database'
If I click the database in Server Management Studio, the current database status is not changed to clicked database and subtree nodes(like Table, Security and so on) are not displayed with message 'cannot access to the database' eventhough if I click other databases, the current database status is changed to clicked database.
Also, I tried to change the owner of the localdb(database) through below code but it seems the execution failed with result '-1' with 'sa' and when trying with 'KayLee-PC\KayLee' which I always login to Windows O/S, error message is like 'KayLee-PC\KayLee is already an owner(exist) of this database'
SqlConnection dbownerchange_Conn = new SqlConnection();
dbownerchange_Conn.ConnectionString = dbownerchange_ConnectionString;
dbownerchange_Conn.Open();
SqlCommand dbownerchange_comm = new SqlCommand();
dbownerchange_comm.Connection = dbownerchange_Conn;
dbownerchange_comm.CommandText = "EXEC sp_changedbowner 'sa'";
dbownerchange_comm.ExecuteNonQuery();
dbownerchange_Conn.Close();
Simply, If we need to move(copy) Microsoft localdb file to another place(computer), how can I do this successfully?
Must we detach before move the localdb file? If so, I'm worried there're always people who don't follow guideline by running detach function.
I've tried several scenarios to understand how SQL server is working. The conclusion is we need to detach first and re-attach to same or different machine(computer). Then, I could have been successful to move to another computer.
However, a single process of backup and restoring localdb to another machine(computer) doesn't work. Furthermore, if we detach localdb(database file .mdf) first, SQL server no more recognizes the localdb database and we cannot run backup command for the localdb.
Conclusively and simply, if we want to move localdb (microsoft database .mdf file) to other local server(computer, machine), we're needed to just detach the localdb from master database in computer A and copy the files and re-attach to another master database of computer B.
Hope this helps someone else..

C# Project - InstallShield , MySql error when run after installation

I have a project in C# which is created in Visual Studio 2013. I want to create an installer using Install Shield free version. I created an installer and trying to run it on other computer but, when I run it and trying to log into program, I have problems about mysql database. Error message is:
Unhandled exception has occured in you application. If you click Continue, the application will ignore this error and attempt to continue. If you click Quit, the application will close immediately.
Cannot connect.
If I click on details button, I have a serie of errors which refers on Mysql. Example:
System.Exception: Cannot connect ---> MySql.Data.MySqlClient.MySqlException: Unable to connect to any of the specified MySQL hosts.
at MySql.Data.MySqlClient.NativeDriver.Open()
at MySql.Data.MySqlClient.Driver.Open()
at MySql.Data.MySqlClient.Driver.Create(MySqlConnectionStringBuilder settings)
at MySql.Data.MySqlClient.MySqlPool.GetPooledConnection()
at MySql.Data.MySqlClient.MySqlPool.TryToGetDriver()
at MySql.Data.MySqlClient.MySqlPool.GetConnection()
at MySql.Data.MySqlClient.MySqlConnection.Open()
at simulator.ConnConfig.getConnection()
simulator is the name of the project. ConnConfig is a class where is the connection and getConnection() is a function from ConnConfig which return connection. II tried to install on another computer .NET Framework 4.5.2, SQL Server, but also didn't worked.
In my project, I use localhost server where I have a database with 2 tables. My question is, is there any possibility to add that localhost database to installer and use it on another computer? And what redistributables requires this operation? Also, I have installed on computer .NET Framework 4.5, Sql Server 2012..but when I try do add them in InstallShield via Redistributables, but it keeps saying that Needs to be downloaded. Why?
UPDATE
I have this Class where I make the conenction. But I receive error: Additional information: Illegal characters in path. at that line:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Data.SQLite;
namespace simulator
{
class ConnConfig
{
private static string conn = "Data Source=c:\aplicatie.db;Version=3;Password=myPassword;";
public static SQLiteConnection connect = null;
private ConnConfig()
{
}
public static SQLiteConnection getConnection()
{
SQLiteConnection connect = null;
try
{
connect = new SQLiteConnection(conn);
connect.Open();// here I receive the error
return connect;
}
catch (SQLiteException e)
{
throw new Exception("Cannot connect", e);
}
}
}
}
UPDATE 3
In that class I make the connection to database. In the other forms I just use tables and their data. For connection to program, I use a login form which uses this class to getConnection(). I created that database by adding an ADO.NET in simulator project. And with that, it comes those 2 tables that I already have in localhost server. So, Is ok if I have to create another empty database with new tables, but where to include that code or how to use it, because I don't get how that script works..where should I put it?
If your database is going to be installed on each client and your tables are not massive you might want to look at something lighter like SQLite which doesn't need any installation just the dlls and is very fast and efficient and only runs when your program does.
As for for the Needs to be Downloaded issue, it seems you have not setup your prerequisite correctly, you an correct this by following the steps in this article
Adding InstallShield Prerequisites, Merge Modules, and Objects to Basic MSI and InstallScript MSI Projects
You might want to look into determining if MySQL is the right solution for you.
SQLite vs MySQL vs PostgreSQL: A Comparison Of Relational Database Management Systems
And to see the limitations of SQLite SQLite
Because honestly seems like overkill to install MySQL on every system. If you had one server with MySQL on the network, okay. But on every system seems like a bad idea.
As far as connecting to an SQLite database here is a List of Connection Strings for SQLite
See this topic on how to create Databases and tables Create SQLite Database and table
My guess is your program doesn't bundle up the database alongside the setup upon deployment. This may be due to the fact that you didn't mark your database as a Data File in the Project Files. Try this, right click on your project name in Solution Explorer and select Properties from Menu. From the horizontal tabs click on the Publish Tab. Under Install Mode and Settings click the Application Files button. A dialog box appears with all Application files. Set your database Publish Status to Data File from the drop down on the corresponding cell. This way your database will be bundled together with the setup upon publishing. Hope this helps.
You can access SQLite via ODBC.

oracle connection string with SID in c#

Hi I have to connect to an Oracle Database( about which I know a little) using a windows application.
The windows application will not necessarily be in the same system.
I just needed the connection string.
So I Used Add connection functionality in Visual Studio 2014 to test the connection and get the string.
eedb is the SID which i read in stackoverflow question
Now using above, i was able to connect to the database using this functionality and even in my visual studio server explorer all the tables of the oracle database were showing but I needed to use the connection string in the windows application.
So I used following string:
DATA SOURCE=172.31.8.21:1521/eedb;USER ID=PDB_E_GND_R
I added password too to this string as
DATA SOURCE=172.31.8.21:1521/eedb;USER ID=PDB_E_GND_R;PASSWORD=123
when i run the application i get error.
System.Data.OracleClient.OracleException: ORA-01017: invalid username/password; logon denied.
So :
Why I am getting this error. Now some may mark this question as duplicate and even point out the answer can be found in issue stackoverflow question
Coz if this was the case I would have been unable to establish connection through add connection functionality of Visual Studio at all.
Please note: I added the reference: Oracle.DataAccess
And also for a programmer like me who has very little knowledge regarding the oracle.
How I can know which connection string I have to use for a particular oracle db.
Try the following connection string EZ connect does not seem to be so EZ
data source=(DESCRIPTION =(ADDRESS_LIST =(ADDRESS = (PROTOCOL = TCP)(HOST = 172.31.8.21)(PORT = 1521)))(CONNECT_DATA =(SERVICE_NAME = eedb)));USER ID=PDB_E_GND_R;PASSWORD=123

Having trouble connecting C# executable to database file on remote computer

Using VC# I've created a staff management app that, upon its first run, is expected to query the user for the path to a (.mdf) database which will reside on a remote computer. A resulting path may be something like
string dbPath = #"P:\remoteComputer\public\StaffTool\ExamplePersonnelDatabase.mdf";
Then I'm placing this string into a connection string template as so:
string dbConnectTemplate = #"Data Source=.\SQLEXPRESS;AttachDbFilename={0};Integrated Security=True;Connect Timeout=30;User Instance=True";
string dbConnectionString = String.Format(dbConnectionTemplate,dbPath);
Then I'm attempting to connect to the database LINQ to SQL style
ManagementDBDataContext db = new ManagementDBDataContext(
dbConnectionString);
At this point, an error pop's up stating that
The file "P:\remoteComputer\public\StaffTool\ExamplePersonnelDatabase.mdf" is on a network path that is not supported for database files.
An attempt to attach an auto-named database for file P:\remoteComputer\public\StaffTool\ExamplePersonnelDatabase.mdf failed. A database with the same name exists, or specified file cannot be opened, or it is located on UNC share.
As I am relatively new to databases, I completely do not understand this message. And obviously, the file is not on a UNC share.
Any ideas?
Jim Lamb recommended that I connect to an instance of SQL server running remotely. Considering that I'm using LINQ to SQL, what refactoring do I have to do to make this happen? Other ideas still welcome - especially "push this button and everything will work" solutions.
Another clue: A coworker said that there used to be some way to work through Control Panel->Administrative Tools->Data Sources(ODBC) so that a remote database could be viewed from my computer as if it was local. The coworker didn't know any more details besides this.
You are attempting to connect to a database file on another machine over a network connection, which isn't supported by SQL Express. You'll need to make a local copy and attach to that, or connect to an instance of SQL that's running on the same machine as the MDF file.

Categories