Search in SQLite using QueryAsync and latin words.

Luiz Alexandre Ruiz 1 Reputation point
2020-12-27T21:07:59.747+00:00

I have a problem from search latin words in SQLite.

Example:

inicial = 100;
final = 200;
textoBusca = "Muça";

My code

var data = await conexaoSQLite..QueryAsync<Produto>($"SELECT * FROM Produto WHERE CP_Valor >= ? AND CP_Valor <= ? AND Descricao_Produto LIKE ? ORDER BY Descricao_Produto", inicial, final, "%" + textoBusca + "%");

In this case my result is empty, I believe this error occur because "ç".

Xamarin
Xamarin
A Microsoft open-source app platform for building Android and iOS apps with .NET and C#.
5,291 questions
SQL Server
SQL Server
A family of Microsoft relational database management and analysis systems for e-commerce, line-of-business, and data warehousing solutions.
12,654 questions
0 comments No comments
{count} votes

2 answers

Sort by: Most helpful
  1. Leon Lu (Shanghai Wicresoft Co,.Ltd.) 68,016 Reputation points Microsoft Vendor
    2020-12-28T02:57:03.463+00:00

    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.

    51446-image.png

    After execute the query.

    51523-image.png

    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.

    0 comments No comments

  2. Luiz Alexandre Ruiz 1 Reputation point
    2021-01-03T17:38:40.963+00:00

    @Leon Lu (Shanghai Wicresoft Co,.Ltd.) Thanks for your reply.

    I saw your answer one day after and I changed my code, but I still the same problem.
    Yesterday I make our project and it run correctly. I hunting and I think why in my project is not work... :(
    I figured out, is because I used to Uppercase in my DB.

    Try this in your project.

    List<Produto> produtos=  await App.Database.GetProdutoByTextAsync(100,200, "Muça");  
    

    change for

    List<Produto> produtos=  await App.Database.GetProdutoByTextAsync(100,200, "MUÇA");  
    

    And you see the problem.

    I have other problem.

    List<Produto> produtos=  await App.Database.GetProdutoByTextAsync(100,200, "Muca");  
    

    I change "ç" to "c", after that I have the same problem.

    "I still learning english... :) And I not use google translator... :)"