read a .db file in C# - 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.

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 find connection string sql server via code not by properties

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.

Add New Data Source and code in connection with mismatch

I'm doing the project with c # sqlite
I'm starting to connect with the code.
updating, deleting, listing procedures
I'm with the code
string connect = #"Data source=" + System.Windows.Forms.Application.StartupPath + "\\yedek\\DUKKAN.db3; Journal Mode=Off"
this connection good work.
but Add New Data Source connection this map wrong
image
http://i.imgur.com/DSEsGxS.png
If I choose to browse on different computers, this error "unable to open database"
I use the other connection for reporting (for dataset)
consequently
the database is running
reporting does not work
this project screen (work) database insert, select and update work
http://i.imgur.com/kZO2XT8.png
this project report(use microsoft report viewer) not work
http://i.imgur.com/SJdetwG.png
You will need to specify the full path and file name in the Add Connection dialog (http://i.imgur.com/DSEsGxS.png). Instead of "yedek\DUKKAN.db3" it should read something like "c:\Users\yedek\DUKKAN.db3". Use the "Browse..." button to find the db3 file.

C# and SQLite: "no such table error" when using relative path?

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

Writing into excel file with OLEDB

Does anyone know how to write to an excel file (.xls) via OLEDB in C#? I'm doing the following:
OleDbCommand dbCmd = new OleDbCommand("CREATE TABLE [test$] (...)", connection);
dbCmd.CommandTimeout = mTimeout;
results = dbCmd.ExecuteNonQuery();
But I get an OleDbException thrown with message:
"Cannot modify the design of table
'test$'. It is in a read-only
database."
My connection seems fine and I can select data fine but I can't seem to insert data into the excel file, does anyone know how I get read/write access to the excel file via OLEDB?
I was also looking for and answer but Zorantula's solution didn't work for me.
I found the solution on http://www.cnblogs.com/zwwon/archive/2009/01/09/1372262.html
I removed the ReadOnly=false parameter and the IMEX=1 extended property.
The IMEX=1 property opens the workbook in import mode, so structure-modifying commands (like CREATE TABLE or DROP TABLE) don't work.
My working connection string is:
"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=workbook.xls;Mode=ReadWrite;Extended Properties=\"Excel 8.0;HDR=Yes;\";"
You need to add ReadOnly=False; to your connection string
Provider=Microsoft.Jet.OLEDB.4.0;Data Source=fifa_ng_db.xls;Mode=ReadWrite;ReadOnly=false;Extended Properties=\"Excel 8.0;HDR=Yes;IMEX=1\";
I also had the same problem. Only remove the extended property IMEX=1. That will solve your problem. Your table will be created in your Excel file...
A couple questions:
Does the user that executes your app (you?) have permission to write to the file?
Is the file read-only?
What is your connection string?
If you're using ASP, you'll need to add the IUSER_* user as in this example.
How do I check the permissions for writing to an excel file for my application (I'm using excel 2007)?
The file is not read only, or protected (to my knowledge).
My connection String is:
"Provider=Microsoft.Jet.OLEDB.4.0;Data
Source=fifa_ng_db.xls;Mode=ReadWrite;Extended
Properties=\"Excel
8.0;HDR=Yes;IMEX=1\""
Further to Michael Haren's answer. The account you will need to grant Modify permissions to the XLS file will likely be NETWORK SERVICE if this code is running in an ASP.NET application (it's specified in the IIS Application Pool). To find out exactly what account your code is running as, you can do a simple:
Response.Write(Environment.UserDomainName + "\\" + Environment.UserName);
I was running under ASP.NET, and encountered both "Cannot modify the design..." and "Cannot locate ISAM..." error messages.
I found that I needed to:
a) Use the following connection string:
Provider=Microsoft.Jet.OLEDB.4.0;Mode=ReadWrite;Extended Properties='Excel 8.0;HDR=Yes;';Data Source=" + {path to file};
Note I too had issues with IMEX=1 and with the ReadOnly=false attributes in the connection string.
b) Grant EVERYONE full permissions to the folder in which the file was being written. Normally, ASP.NET runs under the NETWORK SERVICE account, and that already had permissions. However, the OleDb code is unmanaged, so it must run under some other security context. (I am currently too lazy to figure out which account, so I just used EVERYONE.)

Categories

Resources