Hello,
Welcome to our Microsoft Q&A platform!
conexaoSQLite..QueryAsync<Produto>()
I saw above code that have two point before QueryAsync
method. And I create an demo, and with latin words. My QueryAsync() command like following code.
public async Task<List<Produto>> GetProdutoByTextAsync(int inicial, int final,string textoBusca)
{
object[] sss = { inicial, final, "%" + textoBusca + "%" };
var data = await Database.QueryAsync<Produto>("SELECT * FROM Produto WHERE CP_Valor >= ? AND CP_Valor <= ? AND Descricao_Produto LIKE ? ORDER BY Descricao_Produto", sss);
return data;
}
I can query it successfully with following code.
private async void Button_Clicked_1(object sender, EventArgs e)
{
List<Produto> produtos= await App.Database.GetProdutoByTextAsync(100,200, "Muça");
ProdutoView.ItemsSource = produtos;
}
I put the query result to listview. Here is running screenshot.
Here is all of records in DB.
After execute the query.
Here are all of my code(If you still cannot get records with about code, you can create an demo with all of my code), I install sqlite-net-pcl
with 1.7.335
App.xaml.cs
.
public App()
{
InitializeComponent();
NavigationPage navigationPage= new NavigationPage( new MainPage());
MainPage = navigationPage;
}
static ProdutoItemDatabase database;
public static ProdutoItemDatabase Database
{
get
{
if (database == null)
{
database = new ProdutoItemDatabase();
}
return database;
}
}
MainPage.xaml
<StackLayout>
<Button Text="add" Clicked="Button_Clicked"></Button>
<Button Text="get" Clicked="Button_Clicked_1"></Button>
<ListView x:Name="ProdutoView"
>
<ListView.ItemTemplate>
<DataTemplate>
<TextCell Text="{Binding Descricao_Produto}" />
</DataTemplate>
</ListView.ItemTemplate>
</ListView>
</StackLayout>
MainPage.xaml.cs
public partial class MainPage : ContentPage
{
public MainPage()
{
InitializeComponent();
}
protected async override void OnAppearing()
{
base.OnAppearing();
ProdutoView.ItemsSource = await App.Database.GetProdutoAsync();
}
private async void Button_Clicked(object sender, EventArgs e)
{
Produto produto= new Produto() { Descricao_Produto = "tttMuçabbb", CP_Valor = 170 };
Produto produto2 = new Produto() { Descricao_Produto = "test", CP_Valor = 120 };
Produto produto3 = new Produto() { Descricao_Produto = "Muça", CP_Valor = 150 };
await App.Database.SaveItemAsync(produto2);
await App.Database.SaveItemAsync(produto);
}
private async void Button_Clicked_1(object sender, EventArgs e)
{
List<Produto> produtos= await App.Database.GetProdutoByTextAsync(100,200, "Muça");
ProdutoView.ItemsSource = produtos;
}
}
ProdutoItemDatabase.cs
using SQLite;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace App14
{
public static class TaskExtensions
{
// NOTE: Async void is intentional here. This provides a way
// to call an async method from the constructor while
// communicating intent to fire and forget, and allow
// handling of exceptions
public static async void SafeFireAndForget(this Task task,
bool returnToCallingContext,
Action<Exception> onException = null)
{
try
{
await task.ConfigureAwait(returnToCallingContext);
}
// if the provided action is not null, catch and
// pass the thrown exception
catch (Exception ex) when (onException != null)
{
onException(ex);
}
}
}
public static class Constants
{
public const string DatabaseFilename = "ProdutoSQLite.db3";
public const SQLite.SQLiteOpenFlags Flags =
// open the database in read/write mode
SQLite.SQLiteOpenFlags.ReadWrite |
// create the database if it doesn't exist
SQLite.SQLiteOpenFlags.Create |
// enable multi-threaded database access
SQLite.SQLiteOpenFlags.SharedCache;
public static string DatabasePath
{
get
{
var basePath = Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData);
return Path.Combine(basePath, DatabaseFilename);
}
}
}
public class ProdutoItemDatabase
{
static readonly Lazy<SQLiteAsyncConnection> lazyInitializer = new Lazy<SQLiteAsyncConnection>(() =>
{
return new SQLiteAsyncConnection(Constants.DatabasePath, Constants.Flags);
});
static SQLiteAsyncConnection Database => lazyInitializer.Value;
static bool initialized = false;
public ProdutoItemDatabase()
{
InitializeAsync().SafeFireAndForget(false);
}
async Task InitializeAsync()
{
if (!initialized)
{
if (!Database.TableMappings.Any(m => m.MappedType.Name == typeof(Produto).Name))
{
await Database.CreateTablesAsync(CreateFlags.None, typeof(Produto)).ConfigureAwait(false);
}
initialized = true;
}
}
public Task<List<Produto>> GetProdutoAsync()
{
// SQL queries are also possible
return Database.QueryAsync<Produto>("SELECT * FROM [Produto]");
}
public async Task<List<Produto>> GetProdutoByTextAsync(int inicial, int final,string textoBusca)
{
object[] sss = { inicial, final, "%" + textoBusca + "%" };
var data = await Database.QueryAsync<Produto>("SELECT * FROM Produto WHERE CP_Valor >= ? AND CP_Valor <= ? AND Descricao_Produto LIKE ? ORDER BY Descricao_Produto", sss);
return data;
}
public Task<int> SaveItemAsync(Produto item)
{
if (item.ID != 0)
{
return Database.UpdateAsync(item);
}
else
{
return Database.InsertAsync(item);
}
}
}
}
Produto.cs
using SQLite;
using System;
using System.Collections.Generic;
using System.Text;
namespace App14
{
public class Produto
{
[PrimaryKey, AutoIncrement]
public int ID { get; set; }
public int CP_Valor { get; set; }
public string Descricao_Produto { get; set; }
}
}
Best Regards,
Leon Lu
If the response is helpful, please click "Accept Answer" and upvote it.
Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.