How to use pre-designed SQLite in UWP project? - sqlite

I have a SQLite database from another project and I want to use it in a UWP application. But I don't know how to import this database to the project and!

I can create a new Database and use it but I don't know how to copy database file from project. I use from SQLite.Net-PCL nuget package.
For how to access an exist file, there are two locations that all apps can access. Details please reference the file-access-permissions.
One is Application install directory. As #Henk Holterman said, you can import your existed database file into your project by right-click one folder and select Add->Existing item to add your database file to the project. Pay attention the file's Build action property need to be set to content. Details please see the following picture.
Suppose you already had a database file Sun.db added to the Assets folder, and now you can connect to it by the following code( use the SQLite.Net-PCL Nuget Package).
path = Path.Combine(Windows.ApplicationModel.Package.Current.InstalledLocation.Path, #"Assets\Sun.db");
using (SQLite.Net.SQLiteConnection conn = new SQLite.Net.SQLiteConnection(new SQLite.Net.Platform.WinRT.SQLitePlatformWinRT(), path))
{
}
But this folder is read only. Another location is Application data locations which can read/write. You can copy the database file from install directory to the application data directory for using. The following code example is for connecting a database file that in the local folder.
StorageFile file;
try
{
file = await Windows.Storage.ApplicationData.Current.LocalFolder.GetFileAsync("Sun.db");
}
catch
{
StorageFile Importedfile = await StorageFile.GetFileFromApplicationUriAsync(new Uri("ms-appx:///Assets/Sun.db"));
file = await Importedfile.CopyAsync(Windows.Storage.ApplicationData.Current.LocalFolder);
}
path = file.Path;
using (SQLite.Net.SQLiteConnection conn = new SQLite.Net.SQLiteConnection(new SQLite.Net.Platform.WinRT.SQLitePlatformWinRT(), path))
{
conn.CreateTable<User>();
}

Related

Cant find sql lite file on android

I created a SQL Lite database and embbed in my app as a android asset the question is where the heck is the file stored on the device I used the following code to access the database
public Database()
{
var path = Path.Combine(System.Environment.
GetFolderPath(System.Environment.
SpecialFolder.Personal), "StockApp.db");
Console.Write("OPening Database dbPath" + path);
database = new SQLiteAsyncConnection(path);
}
When I search for the file i cannot find it but when I use the internal debugger it puts the file at the following location.
It finds it fine and it does place a row in the table
path "/data/user/0/com.companyname.StockApp/files/StockApp.db" string
But where is the actual file I have a STK7 DEVICE for testing so Do any ideas?

How can I install a database in a titanium alloy project?

I have been trying to install a tiny simple database into my titanium project with the code from the documentation and trying different tweaks as suggested by a variety of sources. But I cannot get it to work, I get errors like "no such table" or resultset is null. Currenty my code looks like this:
var db = Ti.Database.install('../assets/exercises.db', 'exercisesDB');
Ti.API.info('installed '+ db.getName() );
db.close();
Ti.API.info('closed db' );
db = Ti.Database.open('exercisesDB');
Ti.API.info('reopened db' );
//Ti.API.info(db.getName() );
var exercisesDBRS = db.execute('SELECT id,name FROM exercise');
I have tried putting the database file exercises.db in the assets folder and in the Resources folder but I'm getting no where. I created the db file with "DB Browser for SQLite" ver 3.9.1 on OSX Sierra - is it compatible with appcelerator alloy projects? My current code produces the error "no such table" on the execute call. I assure you the db file has an exercise table.
PS, full code in new projects index.js file is as follow:
var db = Ti.Database.install('exercises.sqlite', 'exercisesDB');
Ti.API.debug('installed '+ db.getName() );
db.close();
Ti.API.debug('closed db' );
db = Ti.Database.open('exercisesDB');
Ti.API.debug('reopened db' );
var exercisesDBRS = db.execute('SELECT id, name FROM exercise');
Ti.API.debug('executed select');
Ti.API.debug(' rowcount== '+ exercisesDBRS.rowCount);
while (exercisesDBRS.isValidRow()) {
var exId = exercisesDBRS.fieldByName('id');
var exName = exercisesDBRS.fieldByName('name');
Ti.API.debug("Exercise: "+exId + ' ' + exName );
exercisesDBRS.next();
}
exercisesDBRS.close();
db.close();
function doClick(e) {
alert($.label.text);
}
$.index.open();
New project but same code and a copy of the same database file in the app/lib folder. Same error - no such table on the execute line when tested in android, works fine in iOS sim.
As per the docs, your external database should be located at the same place where you are running the below code:
var db = Ti.Database.install('../assets/exercises.db', 'exercisesDB');
There's no need to use ../assets/. You can simply refer the database without it because everything you put in assets folder is moved to respective Resources->iphone/android folder.
You can always use Ti.Database.install method for external database because after installing a database once, it will behave like Ti.Database.open('exercisesDB') method.
Coming to your primary concern, you can always safely put your database file in app -> lib folder (create lib folder if it's not present and put db file in there then).
After putting the db file there, you can always use below code:
var db = Ti.Database.install('exercises.db', 'exercisesDB');
Though, I have never used .db extension, instead I have always used .sqlite format (since docs also says SQLite database) and it has worked 100% correct every time.
So you can try this process by changing the database format to .sqlite and put it in app->lib folder. It will definitely work and after verifying you can use same code on using a .db file and see if it's supported or not.
On Android: Follow these steps:
1- In your PC, go to the project's root directory, delete build and Resources folders.
2- On device, clear app data from Settings and then delete the app.
3- Now install the app again with the same code and flow as I mentioned here.
If it's working fine for iOS sim, then it should also work for Android (only some cleaning issues are there or your previous database is still there).

How to save generated file temporarily in servlet based web application

I am trying to generate a XML file and save it in /WEB-INF/pages/.
Below is my code which uses a relative path:
File folder = new File("src/main/webapp/WEB-INF/pages/");
StreamResult result = new StreamResult(new File(folder, fileName));
It's working fine when running as an application on my local machine (C:\Users\userName\Desktop\Source\MyProject\src\main\webapp\WEB-INF\pages\myFile.xml).
But when deploying and running on server machine, it throws the below exception:
javax.xml.transform.TransformerException:
java.io.FileNotFoundException
C:\project\eclipse-jee-luna-R-win32-x86_64\eclipse\src\main\webapp\WEB INF\pages\myFile.xml
I tried getServletContext().getRealPath() as well, but it's returning null on my server. Can someone help?
Never use relative local disk file system paths in a Java EE web application such as new File("filename.xml"). For an in depth explanation, see also getResourceAsStream() vs FileInputStream.
Never use getRealPath() with the purpose to obtain a location to write files. For an in depth explanation, see also What does servletcontext.getRealPath("/") mean and when should I use it.
Never write files to deploy folder anyway. For an in depth explanation, see also Recommended way to save uploaded files in a servlet application.
Always write them to an external folder on a predefined absolute path.
Either hardcoded:
File folder = new File("/absolute/path/to/web/files");
File result = new File(folder, "filename.xml");
// ...
Or configured in one of many ways:
File folder = new File(System.getProperty("xml.location"));
File result = new File(folder, "filename.xml");
// ...
Or making use of container-managed temp folder:
File folder = (File) getServletContext().getAttribute(ServletContext.TEMPDIR);
File result = new File(folder, "filename.xml");
// ...
Or making use of OS-managed temp folder:
File result = File.createTempFile("filename-", ".xml");
// ...
The alternative is to use a (embedded) database or a CDN host (e.g. S3).
See also:
Recommended way to save uploaded files in a servlet application
Where to place and how to read configuration resource files in servlet based application?
Simple ways to keep data on redeployment of Java EE 7 web application
Store PDF for a limited time on app server and make it available for download
What does servletcontext.getRealPath("/") mean and when should I use it
getResourceAsStream() vs FileInputStream
just use
File relpath = new File(".\pages\");
as application cursor in default stay into web-inf folder.

Replace/overwrite local SQLite database file [WP8]

I' ve got a local pre-populated SQLite database file in my main project folder from which I get the needed data in my application. I establish a connection using:
SQLiteAsyncConnection conn = new SQLiteAsyncConnection("mydb.sqlite");
This file gets somehow updated (not locally & not by me or the user) so, after checking for new versions in my application, I have to overwrite my .sqlite file with the new one I download for that purpose.
(Also, there is a property called 'Build Action' which needs to be changed after adding a new db file.)
Is that possible? If so, have you got any suggestions?
edit:
I've managed to store the downloaded file in LocalStorage and then tried to copy and replace my database using this code:
StorageFile originalFile = await
ApplicationData.Current.LocalFolder.GetFileAsync("mydb.sqlite");
StorageFile downloadedFile = await ApplicationData.Current.LocalFolder.GetFileAsync("mydb2.sqlite");
await downloadedFile.CopyAndReplace(originalFile);
Now I'm getting this error:
'Windows.Storage.StorageFile' does not contain a definition for 'CopyAndReplace' and no extension method 'CopyAndReplace' accepting a first argument of type 'Windows.Storage.StorageFile' could be found
It's strange because it works fine in a new project I created. Could that be a conflict in the assembly references?

File Not found in exe of wpf application

When publishing the WPF application and generate an exe, I am unable to get the files which are placed in the templates-folder. When I copy my folder and files to bin it works, or if use
string StartUpPath = AppDomain.CurrentDomain.BaseDirectory.ToString();
// var gparent = Directory.GetParent(Directory.GetParent(Directory.GetParent(StartUpPath).ToString()).ToString()).ToString();
ReportDocument reportDocument = new ReportDocument();
StreamReader reader = new StreamReader(new FileStream(StartUpPath + #"\Templates\Invoice.xaml", FileMode.Open));
This code works fine for my local, but when I generate an exe, these files are not found.
That's because your files aren't in the exe. I had the same problem recently.
It sounds like you need to handle your resources - there are several ways to go about this, and Microsoft has a full explanation here about resources, including the difference between using Linked and Embedded Resources, and links through to other great guides.
I'm assuming you're using Visual Studio, in which case this should work;
right click the file you can't access
select properties (or press ALT + ENTER)
set Build Action to be Resource
set Copy to Output Directory to be Copy if newer
save
... and you should be good to go.
I think it throws an exception because the file doesn't exist on that machine. You can set Build Action to Content and Copy to Output Directory to Copy Always or Copy If Newer on property window.
These settings will make sure that you have the file to your output.

Resources