Android Code Snippet Count The Number of a Given String In a SQLite Column

Discussion in 'Code Snippets' started by Mahares, Sep 9, 2015.

  1. Mahares

    Mahares Well Known Member Licensed User

    Description: To look for any given sub string inside a SQLite table column, similar to @stevel05 code snippet, but here I show the SQL statement equivalent. For example: If my search sub string is 'ic', the country of 'Dominican Republic' will show 2.

    "INSERT INTO tblCountry  VALUES(?)"

    Array As String("CHINA"))
    Array As String("INDIA"))
    Array As String("USA"))
    Array As String("INDONESIA"))
    Array As String("BRAZIL"))
    Array As String("PAKISTAN"))
    Array As String("BANGLADESH"))
    Array As String("NIGERIA"))
    Array As String("RUSSIA"))
    Array As String("JAPAN"))
    Array As String("Test to Count the characters in this test string"))
    Array As String("Central African Republic"))
    Array As String("Democratic Republic of Congo"))
    Array As String("Dominican Republic"))

    'Dim MyString As String = "IA"  'works
        'Dim MyString As String = "o".ToUpperCase  'works
        'Dim MyString As String = "republic".ToUpperCase   'works
        'Dim MyString As String = "test".ToUpperCase    'works
        'Dim MyString As String = "ni".ToUpperCase   'works
        Dim MyString As String = "ic".ToUpperCase   'works

        & MyString & 
    "', '')))/length('" & MyString & "')  AS MyLen FROM tblCountry"

    For i=0 To Cursor1.RowCount-1
    Log(Cursor1.Getstring("COUNTRY") & "  " &  Cursor1.GetInt("MyLen"))

    Tags: SQLite, ExecQuery, replace, Upper, length
    Libray: SQL
  2. Erel

    Erel Administrator Staff Member Licensed User

    You should use ExecQuery2 with a parameterized query instead.
    Peter Simpson likes this.
  3. Mahares

    Mahares Well Known Member Licensed User

    As @Erel suggested, you can alternatively use a parameterized SELECT query to yield the same result set:
    txt="SELECT COUNTRY, (length(COUNTRY)  - length(REPLACE(UPPER(COUNTRY), ?, '')))/length(?)  AS MyLen FROM tblCountry" 
    Array As String(MyString, MyString))
    Erel likes this.
  4. Erel

    Erel Administrator Staff Member Licensed User

    Now it will work if someone searches for: King's Cross, London (and it will also be safe from SQL injections).
  1. This site uses cookies to help personalise content, tailor your experience and to keep you logged in if you register.
    By continuing to use this site, you are consenting to our use of cookies.
    Dismiss Notice