Delphi TFDTable SqLite problems - sqlite

I deployed a sample.s3db SqLite to my Delphi android project.
set folder to:
fdconnection1.params.Database := system.ioutils.TPath.Combine( system.ioutils.TPath.GetDocumentsPath, 'sample.s3db');
in FDConnection1BeforeConnect event.
in Project-Deployment, set folder to assets\internal\ for Android
However, when I run the app, apparently it can find the physical file, but it says my tablename "Customers" is not found.
so in the BeforeConnect code, if I add a CREATE TABLE SQL create code if not exists, then everything works well but of course the table is empty (whereas my deployed sample.s3db is not empty) ... which proves the FILE sample.s3db was found and not corrupted, but somehow the Table was not found.
Even tried to change in BeforeConnect
FDConnection1.Params.Values['OpenMode'] := 'ReadWrite';
but it still doesn't work.
Any ideas the table name does not work?
I tried to change table name to all caps, in case Android is case-sensitive but it also does not work.

I recommend deleting your app from the android. This will clear out your data. Otherwise your new sqlite file is not deployed if the file already exists. This could happen for instance if you made an error in the path at one point in time so sqlite just created an empty database.
Your connection string looks correct and so does your destination path. Just to be safe, you may also want to clear out your other values for your connection.
fdConnection1.ConnectionDefName:= '';

Related

sqlite database location node-red

I have a Node-RED flow. It uses a sqlite node. I am using node-red-node-sqlite. My OS is Windows 10.
My sql database is configured just with name "db" :
My question is, where is located the sqlite database file?
I already search in the following places, but didn't found:
C:\Users\user\AppData\Roaming\npm\node_modules\node-red
C:\Users\user\.node-red
Thanks in advance.
Edit
I am also using pm2 with pm2-windows-service to start Node-RED.
If you don't specify a full path to the file in the Database field it will create the file in the current working directory for the process, which will be where you ran either node-red or npm start.
Use full path location with file name.
It should work i guess.
This isn't a valid answer, just a workaround for those who have the same problem.
I could't find my database file. But inside Node-RED everything worked just great. So. this is what I have done as a workaround:
In Node-RED, make some select nodes to get all data from tables
Store the tables values somewhere (in a .txt file or something like that)
Create your database outside Node-RED, somewhere like c:\sqlite\db.db. Check read/write permissions
Create the tables and insert the values stored from old database
In Node-RED, inside "Database", put the complete path of the database. For example, c:\sqlite\db.db
In my case this was easy because I only had two database with less than 10 rows.
Hope this can help others.
Anyway, still waiting for a valid answer :)

Setting a relative path to sqlite database with Delphi and Firedac

In replacement of my previous question which was confusing and poorly formulated, here is the "real" question.
I would like to known how to set, with Firedac, at runtime, a relative path to a sqlite database located in a subfolder of my application folder.
As Jerry Dodge stated :
Any application should never rely on writable data in the same directory anyway. Also, even if you did, you should make sure all your paths are relative to the application at least.
At the moment, the application I have in mind is portable and I would like the database file to be stored in a sub-folder of the main exe folder.
On the Form.Create event of my main form, is used first
path := ExtractFilePath(Application.ExeName);
And in then for FDConnection :
with FDConnection1 do begin
Close;
with Params do begin
Clear;
Add('DriverID=SQLite');
Add('Database='+path+'Data\sqlite.db');
end;
Open;
end;
I keep on getting an error saying "unable to open database file".
I don't want to set the path to the database file in the FiredDac Connection Editor because then it would be absolute and bound to my machine, right ?
How could I set this path to the database file so that it would work in any configuration, wherever the user puts the application folder ?
Thank you all in advance
Math
As I found my own solution, I decided to post it here for future users who might encounter the same problem (that is to say a Delphi beginner level and the need to link a database file relative to their project exe file).
FIRST STEP was to add a data module to the project. This was done by going to File -> New -> Other -> Delphi Files -> Data Module
SECOND STEP Once the data module added to the project, as my main Application Form makes a call to the database on creation, I had to make sure the Data Module was created first. To achive that, I went to Project -> Options -> Forms and dragged the datamodule in first position of the list of auto created Forms
THIRD STEP was to drop a FDConnection on the datamodule and set all parameters EXCEPT database file.
FOURTH STEP was to add an OnCreate event to the datamodule, to specify the path to the database relative to the application exe and connect. It was done like this :
procedure TDataModule1.DataModuleCreate(Sender: TObject);
begin
path := ExtractFilePath(ParamStr(0));
FDConnection.Params.Add('Database='+path+'Database\sqlite.db');
FDConnection.Connected := True;
end;
FIFTH AND FINAL STEP was to add the datamodule to the uses clause of all other units that needed a connection to the database.
I realize that this solution is far from perfect and that, as very experienced users already stated, storing the database in the same folder (or a sub-folder) as the main application Exe is not a good solution.
Also, I decided to connect to the database on DataModule creation, but another solution could be to connect on demand before triggering the queries and then disconnect. That's up to you and your needs
Thanks to all for your help, tips and advises
Math
PS : please notice I did not check my answer as accepted as the best answer, would not be fair right :-)
Introduction
IMHO
Database path and server name should not be hardcoded in applivcation.
Why ?
When you work on a project, you need to do many things on database connection, setting datasets, query etc. Usualy this is done on working database. Then server name and database path are different from those of the real database.
You should be able to set up server name and path to database easy and without to compile the project. This allows to set properly database connection params on a random computer.
Solution :
Setup the database connection component on design time, do not create it in runtime. Setup all parameters including server name , database path, charset etc. to your working copy of database. This will allow you to set up the other components associated with this database on design time.
(In your answer I see you have done almost the same.)
Save server name, database path and any other parameter you want, to an exterrnal resource, ini file, windows registry or something else. Then get these parameters when application started or before connect to database.
In your case, you use local server and the same path as application, so you don't need to store nothing.
Regarding the question
The code :
with FDConnection1 do begin
Close;
with Params do begin
Clear; <-- this removes all parameters
Add('DriverID=SQLite');
Add('Database='+path+'Data\sqlite.db');
end;
Open;
end;
removes all other parameters except DriverID and Database. Probably the error arise from that.
If you already setting all parameters in FDConnection:
Do not use:
FDConnection.Params.Add('Database='+path+'Data\sqlite.db');
This will add new parameter with the same name, but connection will use the first one.
This explains why everything works in your answer, because you did not set a parameter 'Database' on design time:
THIRD STEP was to drop a FDConnection on the datamodule and set all
parameters EXCEPT database file.
Instead use :
FDConnection.Params.Database := 'Database='+path+'Data\sqlite.db';
You may use this for example in
OnDataModuleCreate or FDConnectionBeforeConnect events
I hope this will be useful.
In android, I couldn't compile with fdConnection opened in design time, then certify it's closed. Your first line didn't work for me, but about takes the goal:
using following expression, it works for me:
FdConnection1.Params.Values['Database'] := GetHomePath
+ PathDelim + 'sqlite.db';
Look that I didn't use subfolder 'Data'. You can try simple first.
If your resources are light and read-olny for end-user, you could pack them direct into exe file. This would give you really portable application, which your user can run from arbitrary place, even from usb flash.
Go to Project->Resources and Images menu, add there you files.
You can access them in runtime with TStream:
var
s: TStream;
{.....}
s:=TResourceStream.Create(hinstance, 'myfile_1', RT_RCDATA);
Some resources you can handle direct in memory. As for sqlite database, you could copy it from app resources to user's documents path:
MyAppPath := Tpath.GetDocumentsPath+'\MyAppName'; // you need System.IOUtils in uses
If not DirectoryExists(MyAppPath) then CreateDir(MyAppPath);
MyDBPath := MyAppPath+'\Data\sqlite.db';
If not FileExists(MyDBPath) then begin
FL:=TFileStream.Create(MyDBPath ,fmCreate);
FL.CopyFrom(s,0); // this will copy your db into 'sqlite.db' file
end;

Using MagicalRecord to prepopulate a database (swift). -wal journal created, however, data not copied to database

(Forgive me since I am not use to posting here. Will do my best)
I am working on an iOS application that will be using a pre-populated database. In my workspace, I have a project for the iOS app and a separate command line tool project to populate the database. I have dragged the database file from the "/Library/Application Support" folder into my iOS project (without using the "Copy Items If Needed"). So when there is a change in the data or additional data is required, I can just run the command line tool to pre-populate the data. From there I will remove the app from the simulator and do a clean. When I run the app, I would think everything would be ok.
It was driving me crazy for the longest but sometimes, I don't see the changes reflected after I remove the app, clean the project and then run. It seems the only way I can get this to work is, after I run the command line tool to pre-populate the database, I have to open the database file using Base, SQLiteStudio or Firefox's sqlite add-on. Once I do that, it seems to work.
When I look in finder, I do see the files .sqlite, sqlite-shm and sqlite-wal. Before opening the database file, I see that the wal file is the biggest (for now it's 2mb). Once I open the file using Base for example, and then close it, the sqlite file is now 2mb.
When the command line is about to finish, I have tried running PRAGMA statements on the file (vacuum, wal-checkpoint) but those did not work. What am I missing here. I also tried using NSManagedObjectContext.MR_defaultContext.saveToPersistentStoreAndWait
I am using the following code to setup and save.
MagicalRecord.setupCoreDataStackWithAutoMigratingSqliteStoreNamed("callithome.sqlite")
MagicalRecord.saveUsingCurrentThreadContextWithBlockAndWait({(context)->Void in
println("Data saved, I hope")})
MagicalRecord.cleanUp()
Any help would be appreciated
You need to enable the DELETE pragma mode for your sqlite store. This will not create the -wal and -shm files. This will make it easier for you to have a single file for use at your pre-populated data store. You will need to use MagicalRecord 3.0 with some of the extra abilities to add custom options to your stores if you'd like o go that route. However, you can still add a store to a coordinator and have that store configured with the proper pragma option as well. That is, MagicalRecord is not necessary if you use normal Core Data.

How to work with LocalDB and EF, without using migrations

I am on VS 2012 RTM, with EF 5. I am doing Code First, but trying to ignore Code Migrations since I am just in development. To avoid them, I have this set
Database.SetInitializer(new DropCreateDatabaseIfModelChanges<SomeContext>());
Occasionally, even when I don't think I've touched the model, it decides to recreate. That's fine. But it usually results in the error
Cannot drop database because it is currently in use.
So I decided to delete the database entirely. I go into VS, go to the "SQL Server Object Explorer", find the DB and delete it. Now I'm stuck at
Cannot attach the file '{0}' as database '{1}'
I had this happen last night and I just fiddled around until it work (shut down tasks, restart VS, changed the DB and file names in the web.config, etc.
So question 1) How do I get out of this state?
But the more important question, how do I prevent myself from getting in this state at all?
The SQL Server Object Explorer window can hold a connection to the database. Closing the window and all windows opened from it releases the connection.
I had the same problem and managed to fix it. The main problem is that EF won't automatically create the database. The solution is not very hard.
First, go to the Solution Explorer and manually create the database. To do this, go to the folder where your database is located (usually App_Data). Right-click on this folder and click on Add -> New Item. Select the Data tab and select SQL Server Database. Make sure you enter the name Entity Framework expects (which is specified in the Cannot attach the file '{0}' as database '{1}' error message).
Then most likely you will get an error message that says that the database does not contain any model metadata. To circumvent this, change your database initialisation to:
Database.SetInitializer(new DropCreateDatabaseAlways<SomeContext>());
Now run the application and the database should be there with tables correctly created. Once this step has been successfully executed, you change change your database initializer back to:
Database.SetInitializer(new DropCreateDatabaseIfModelChanges<SomeContext>());

Sqlite database exception: file is encrypted or is not a database in blackberry?

I am working on a firm application in which I need to create a local database on my device.
I create my local database through create statement[ It works well]
Then I use that file and perform insert operation through fire-fox sqlite plugin, I need to insert aprox 2000 rows at a time so I can not use code. I just run insert manually through sqlite plugin in fir-fox.
After that I just use that file in my place of my local database.
When I run select query through my code, It show Exception:java.lang.Exception: Exception: In create or prepare statement in DBnet.rim.device.api.database.DatabaseException: SELECT distinct productline FROM T_Electrical ORDER BY productline: file is encrypted or is not a database
I got the solution of this problem, I was doing a silly mistake by creating a file manually by right click in my RES folder, that is not correct. We need to create the database completely from SQlite plugin, then it will work fine. "Create data base from SQLITE(FIle too) and perform insertion operation from SQLITE, then it will work fine"
This is very rare problem, but i think it might be helpful for someone like me....!:)
You should check to see if there is a version problem between the SQLite used by your Firefox installation and that on the BlackBerry. I think I had the same error when I tried to build a database file with SQLite version 2.
You also shouldn't need to create the database file on the device. To create large tables I use a Ubuntu machine and the sqlite3 command line. Create the file, create the tables, insert the data and build indexes. Then I just copy the file onto the device in the proper directory.
For me it was a simple thing. One password was set to that db. I just used it and prolem got solved.

Resources