Slides made for the third apointment of the three lessons course "Xamarin Introduction", kept at the Politecnico di Milano.
These are the slides used to present how to use SQLite in a Xamarin.Forms app.
4. Cosa impareremo oggi?
• Conoscere il mondo dei Database
• Realizzare query
• Implementare SQLite in un’app Xamarin.Forms
5. Quando NON usare un Database
• Impostazioni utente
• File di testo
• File di dati serializzati (XML, JSON)
• Immagini
Per tutte queste esigenze, conviene usare il file-system o metodi propri
della piattaforma usata (iCloud, OneDrive, etc)
6. Quando usare un Database
Più in generale, tutte le volte che ho bisogno di archiviare dati che poi
posso voler trasmettere online, tramite per esempio i Mobile Services di
Microsoft Azure.
• Database
8. Introduzione ai database
• Un database è una struttura in grado di memorizzare dati in maniera
ordinata.
• Sui dati memorizzati in un database posso effetturare query per
leggerli o manipolarli in un qualsiasi modo.
• Il database mette a dispozione strumenti per garantire l’integrità e la
coerenza dei dati memorizzati al suo interno.
9. Le tabelle
• I dati vengono memorizzati in tabelle.
• Ogni riga della tabella (detta n-pla) è
univocamente identificata da un attributo
univoco, chiamato chiave primaria.
10. Le query
• Le query servono ad interagire con le tabelle
• Con una query posso:
– visualizzare dati di una tabella, filtrandoli secondo certi criteri
– aggiungere dati ad una tabella
– modificare dati in una tabella
– eliminare dati da una tabella
– incrociare dati tra tabelle (metodi di “join”)
– creare una nuova tabella
11. La prima query
SELECT [selezione verticale]
FROM [nome tabella]
WHERE [selezione orizzontale] LIKE [parametro];
12. Esempi di query
SELECT *
FROM Voti;
SELECT *
FROM Voti
WHERE Matricola=“803012”;
SELECT *
FROM Voti
WHERE Matricola
LIKE ‘%2’;
SELECT *
FROM Voti
WHERE Matricola
NOT LIKE ‘%2’
14. SQLite - Introduzione
• Database open-source adottato da Google, Apple e Microsoft
• SQLite è leggero, veloce e facilmente trasportabile
• Il database viene memorizzato in un singolo file
Pagina ufficiale del progetto: http://sqlite.org/
15. SQLite - Limitazioni
• Alcuni tipi di sintassi avanzate non sono supportati (per
esempio il tipo di dato “Long”)
• Gli unici comandi disponibili per alterare le tabelle sono
RENAME e ADDCOLUMN
• Le “Viste” sono accessibili solo in lettura
Per tutte le altre limitazioni:
http://sqlite.org/limits.html
16. SQLite – Creazione del Database in una PCL Xamarin.Forms
Prima di tutto, bisogna
aggiungere il pacchetto NuGet
ad ogni progetto della soluzione:
https://www.nuget.org/packages/
sqlite-net-pcl/
17. SQLite – Creazione della tabella
La tabella in SQLite viene gestita da una classe (NomeTabella.cs).
public class Person
{
[PrimaryKey, AutoIncrement]
public int ID { get; }
public string FirstName { get; set; }
public string LastName { get; set; }
[MaxLength(3)]
public int Age { get; set; }
}
18. SQLite – Override dei metodi di default
E’ possibile fare un override dei metodi di default, proprio come in C#,
sulle tabelle usate:
public class Person
{
[...]
public override string ToString()
{
return string.Format("[Person: ID={0}, FirstName={1}, LastName={2}]", ID, FirstName, LastName);
}
}
19. SQLite – Colleghiamoci al Database (Portable)
public interface ISQLite {
SQLiteConnection GetConnection();
}
Bisogna creare un file di interfaccia da estendere poi per ogni piattaforma:
E ora vediamo come implementare l’interfaccia su ogni piattaforma!
20. SQLite – Colleghiamoci al Database (iOS)
[assembly: Dependency (typeof (SQLite_iOS))]
public class SQLite_iOS : ISQLite {
public SQLite_iOS () {}
public SQLite.SQLiteConnection GetConnection ()
{
var sqliteFilename = "TodoSQLite.db3";
string documentsPath = Environment.GetFolderPath (Environment.SpecialFolder.Personal);
string libraryPath = Path.Combine (documentsPath, "..", "Library"); // Library folder
var path = Path.Combine(libraryPath, sqliteFilename);
// Create the connection
var conn = new SQLite.SQLiteConnection(path);
// Return the database connection
return conn;
}}
21. SQLite – Colleghiamoci al Database (Android)
[assembly: Dependency (typeof (SQLite_Android))]
public class SQLite_Android : ISQLite {
public SQLite_Android () {}
public SQLite.SQLiteConnection GetConnection ()
{
var sqliteFilename = "TodoSQLite.db3";
string documentsPath = System.Environment.GetFolderPath (System.Environment.SpecialFolder.Personal);
var path = Path.Combine(documentsPath, sqliteFilename);
// Create the connection
var conn = new SQLite.SQLiteConnection(path);
// Return the database connection
return conn;
}}
22. SQLite – Colleghiamoci al Database (Windows Phone)
[assembly: Dependency (typeof (SQLite_WinPhone))]
public class SQLite_WinPhone : ISQLite{
public SQLite_WinPhone () {}
public SQLite.SQLiteConnection GetConnection ()
{
var sqliteFilename = "TodoSQLite.db3";
string path = Path.Combine(ApplicationData.Current.LocalFolder.Path, sqliteFilename);
// Create the connection
var conn = new SQLite.SQLiteConnection(path);
// Return the database connection
return conn;
}}
23. SQLite – Connessione e Creazione prima tabella
SQLiteConnection database = DependencyService.Get<ISQLite> ().GetConnection ();
database.CreateTable<Person>();
Ora finalmente potremo collegarci al Database:
E creare la prima tabella, con la struttura Person definite prima:
24. SQLite – Intereragire con i dati nel database
database.Query<Person>("SELECT * FROM [Person] WHERE [Done] = 0");
Query diretta in SQL nel Database appena creato:
(from i in database.Table< Person>() select i).ToList();
database.Table< Person>().FirstOrDefault(x => x.ID == id);
database.Delete< Person>(id);
Approccio offerto da SQLite.NET
26. SQLite – Più informazioni su SQLite in Xamarin
Qui, oltre a rivedere quanto visto nella Demo, è possibile imparare come si
implementa SQLite anche in un progetto Shared:
http://developer.xamarin.com/guides/cross-platform/xamarin-forms/working-
with/databases/
Preferences – Both iOS and Android offer a built-in mechanism for storing simple key-value pairs of data. If you are storing simple user settings or small pieces of data (such as personalization information) then use the platform’s native features for storing this type of information. For iOS you can also take advantage of iCloud synchronization for this data, both for backup and synchronization for users with multiple devices.
Text Files – User input or caches of downloaded content (eg. HTML) can be stored directly on the file-system. Use an appropriate file-naming convention to help you organize the files and find data.
Serialized Data Files – Objects can be persisted as XML or JSON on the file-system. The .NET framework includes libraries that make serializing and de-serializing objects easy. Use appropriate names to organize data files.
Image files – Although it’s possible to store binary data in the database on a mobile device, it is recommended that you store them directly in the file-system. If necessary you can store the filenames in a database to associate the image with other data. When dealing with large images, or lots of images, it is good practice to plan a caching strategy that deletes files you no longer need to avoid consuming all the user’s storage space.