|
| 1 | +using SQLite; |
| 2 | +using UnityEngine; |
| 3 | + |
| 4 | +namespace Gilzoide.SqliteNet.Samples.Readme |
| 5 | +{ |
| 6 | + public class TestSqliteAsync : MonoBehaviour |
| 7 | + { |
| 8 | + async void Start() |
| 9 | + { |
| 10 | + // 1. Create a connection to the database. |
| 11 | + // The special ":memory:" in-memory database and |
| 12 | + // URIs like "file:///somefile" are also supported |
| 13 | + var path = $"{Application.persistentDataPath}/MyDb.db"; |
| 14 | + Debug.Log($"Opening database '{path}'"); |
| 15 | + var db = new SQLiteAsyncConnection(path); |
| 16 | + |
| 17 | + // 2. Once you have defined your entity, you can automatically |
| 18 | + // generate tables in your database by calling CreateTableAsync |
| 19 | + await db.CreateTableAsync<Player>(); |
| 20 | + |
| 21 | + // 3. You can insert rows in the database using InsertAsync |
| 22 | + // The Insert call fills Id, which is marked with [AutoIncremented] |
| 23 | + var newPlayer = new Player |
| 24 | + { |
| 25 | + Name = "gilzoide", |
| 26 | + }; |
| 27 | + await db.InsertAsync(newPlayer); |
| 28 | + Debug.Log($"Player new ID: {newPlayer.Id}"); |
| 29 | + // Similar methods exist for Update and Delete. |
| 30 | + |
| 31 | + // 4.a The most straightforward way to query for data |
| 32 | + // is using the Table method. This can take predicates |
| 33 | + // for constraining via WHERE clauses and/or adding ORDER BY clauses |
| 34 | + var query = await db.Table<Player>().Where(p => p.Name.StartsWith("g")).ToListAsync(); |
| 35 | + foreach (Player player in query) |
| 36 | + { |
| 37 | + Debug.Log($"Found player named {player.Name} with ID {player.Id}"); |
| 38 | + } |
| 39 | + |
| 40 | + // 4.b You can also make queries at a low-level using the QueryAsync method |
| 41 | + var players = await db.QueryAsync<Player>("SELECT * FROM Player WHERE Id = ?", 1); |
| 42 | + foreach (Player player in players) |
| 43 | + { |
| 44 | + Debug.Log($"Player with ID 1 is called {player.Name}"); |
| 45 | + } |
| 46 | + |
| 47 | + // 5. You can perform low-level updates to the database using the |
| 48 | + // ExecuteAsync method, for example for running PRAGMAs or VACUUM |
| 49 | + await db.ExecuteAsync("VACUUM"); |
| 50 | + } |
| 51 | + } |
| 52 | +} |
0 commit comments