I'm quite new on Android and recently I've faced such issue:
Im using Android Contacts database, specifically Data table. I'm putting there some info with new mimetype and trying to look for this info during search. The problem is, i'm using SQLite LIKE operator which is Case Sensitive for non-latin characters. Another problem is that i can't change databse in any way, because it's android built-in database.
Builder builder = Data.CONTENT_URI.buildUpon();
loader.setSelection(getIndividualsSelection());
query = query.trim();
if( (null != query) && !query.equals("")){
loader.setSelection(Data.MIMETYPE + "='" +
MY_MIMETYPE + "' " + " AND ( " +
MY_DATA_COLUMN +
" LIKE '"+ query + "%' " +
specialCharsEscape + " COLLATE NOCASE)");
loader.setSelectionArgs(null);
loader.setUri(builder.build());
loader.setProjection(MY_PROJECTION);
loader.setSortOrder(MY_SORT_ORDER);
}
This is all inside of onCreateLoader funcion of LoaderCallbacks, where loader is of CursorLoader type. Do You have any idea how to force my SQLite not to be Case Sensitive?
I've tried off course using SQLite functions UCASE and LCASE but it doesn't work. Using Regexp results in exception for this database as well as using MATCH... Will appreciate any help.
Android has localized collations.
To actually be able to use a collation for comparisons, use BETWEEN instead of LIKE; for example:
MyDataColumn BETWEEN 'mąka' COLLATE UNICODE AND 'mąka' COLLATE UNICODE
is the last UTF-8-encodable Unicode character; a Java string probably would encode it with surrogates as "\uDBFF\uDFFF".
Please note that the UNICODE collation is broken in some Android versions.
Related
As per title, I'm current using JDBC on eclipse to connect to my PostgreSQL.
I have been running EXPLAIN ANALYZE statements to retrieve query plans from postgres itself. However, is it possible to store these query plan in a structure that resemble a tree? e.g main branch and sub branch etc. I read somewhere that it is a good idea to store it into xml document first and manipulate it from there.
Is there an API in Java for me to achieve this? Thanks!
try using format xml eg
t=# explain (analyze, format xml) select * from pg_database join pg_class on true;
QUERY PLAN
----------------------------------------------------------------
<explain xmlns="http://www.postgresql.org/2009/explain"> +
<Query> +
<Plan> +
<Node-Type>Nested Loop</Node-Type> +
<Join-Type>Inner</Join-Type> +
<Startup-Cost>0.00</Startup-Cost> +
<Total-Cost>23.66</Total-Cost> +
<Plan-Rows>722</Plan-Rows> +
<Plan-Width>457</Plan-Width> +
<Actual-Startup-Time>0.026</Actual-Startup-Time> +
<Actual-Total-Time>3.275</Actual-Total-Time> +
<Actual-Rows>5236</Actual-Rows> +
<Actual-Loops>1</Actual-Loops> +
<Plans> +
<Plan> +
<Node-Type>Seq Scan</Node-Type> +
<Parent-Relationship>Outer</Parent-Relationship> +
...and so on
I have those line in CSV file and i wanna import those column into database
Notification Identifier / State / Severity / Event Time / Probable Cause / Managed Object / Alarm Type / Additional Text
ALARM / 1347413987 / Outstanding / Critical / Thu, Feb 18, 2016 04:50:22 PM / NeighborDown / 5620SAM tunisiana_ns:.network.ne.5620SAM6_1 SERVICE
service-652:192.168.161.36:routingInstance:ospf-v2:areaSite-0.0.0.0:interface-2 / EquipmentAlarm / "PE9036
Every Line begin with this "ALARM" and my separator is "/"
Please help me to import this data to a MySQL DB.
Please refer to the documentation for LOAD DATA INFILE here.. http://dev.mysql.com/doc/refman/5.7/en/load-data.html
You can use csv friendly characters in
FIELDS TERMINATED BY ',' ENCLOSED BY '' ESCAPED BY '\\'
LINES TERMINATED BY '\n' STARTING BY ''
Also there are certail GUI tools like SQLyog, which give a direct and an easy way to import CSV files partly or completely into your table on the server.
As they suggest in the comments a better way is:
String esquel = " LOAD DATA LOCAL INFILE '" + path +
"' INTO TABLE tableName " +
" FIELDS TERMINATED BY \'/\' +
" LINES TERMINATED BY \'\\n\'";
Easy way to do this is to use a library like opencsv
i have on Error :
ou have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '+' at line 1
and this is the query:
query = " LOAD DATA LOCAL INFILE '" + "D:\\alarm.csv" + "' INTO TABLE alarm " +" FIELDS TERMINATED BY \'/\' + ";
To prevent from SQL injections, OWASP encodes characters received.Below is the code implemented for org.owasp.esapi.codecs.OracleCodec.java class
//Default implementation that should be overridden in specific codecs. Encodes ' to '' Encodes ' to '' (according to doc)
public String encodeCharacter( char[] immune, Character c ) {
if ( c.charValue() == '\'' )
return "\'\'";
return ""+c;
}
How does above help for the prevention of SQL injection?Please explain.
Using the guidelines at OWASP, multiple test cases can be found here.
The snippet of code you're looking at here defends against someone trying to escape out of the query to run their own arbitrary command.
if ( c.charValue() == '\'' )
If the input value is equal to ASCII char value 0x27 (a single quote)
return "\'\'";
Escape the single quote.
Oracle escaping is here.
Lets say your query is "select * from users where id = \'" + request.getParameter("id")
By not escaping single-quotes, an input like this:
request.setParameter("id", "\' OR 1=1;"); would result in returning all the information in that table by changing the final, non-Java formatted query to select * from users where id = '' OR 1=1;
I highly recommend you download the WebGoat program, and follow its lessons. It will teach you how to use SQL injection, and many other basic web attacks. And the ESAPI swingset will help you learn how to mitigate them.
Here explains very well for oracle and others DBMS:
https://www.owasp.org/index.php/SQL_Injection_Prevention_Cheat_Sheet
But rule n. 1 to prevent SQL injection is not to use query concatenation but instead prepared statements! With prepared statements there is no need to encode any parameter (set by sql api) and there are also DB performance optimizations.
I got a little question about databases and android. I got this code:
sampleDB = this.openOrCreateDatabase(SAMPLE_DB_NAME, MODE_PRIVATE, null);
sampleDB.execSQL("CREATE TABLE IF NOT EXISTS " +
SAMPLE_TABLE_NAME +
" (LastName VARCHAR, FirstName VARCHAR," +
" Country VARCHAR, Age INT(3));");
sampleDB.execSQL("INSERT INTO " +
SAMPLE_TABLE_NAME +
" Values ('Makam','Sai Geetha','India',25);");
and to read:
if (c != null ) {
if (c.moveToFirst()) {
do {
String firstName = c.getString(c.getColumnIndex("FirstName"));
int age = c.getInt(c.getColumnIndex("Age"));
results.add("" + firstName + ",Age: " + age);
}while (c.moveToNext());
}
}
With this code, I make and read the database, and insert some info in it. And print it on the screen, this all works :)
Now the part I can't figure out:
I use myPHPadmin (with xampp),
I made the exact database as I do in the code.
But how do I connect, so my code reads that database.
It is a local database for now (127.0.0.1).
Is it possible to connect a local database? (if so, could you tell me how to)
Do you need PHP, or can you do everything in (Android) Java code?
I am totally new with databases, so sometimes it confusing for me.
Please put me in the good direction.
If you need more information for the question or something else, please let me know.
It is a local database for now (127.0.0.1).
In Android you have to use 10.0.2.2 or System's Static IP.
Write a PHP script (You can also use other but PHP its easy to implement) to manage the database and run this script using HTTP protocol from the android system.
These Tutorials might help you:
Step-by-Step-Method-to-Access-Webservice-from-Andr
Web Services - An XML-RPC Client for Android
As far as I'm aware there is no MySQL library for android. But you can use the HttpPost to send data to a server side script (such as PHP) and then return it in a format you can parse in your Android application.
There's a nice tutorial on how to achieve this here: http://www.helloandroid.com/tutorials/connecting-mysql-database
Here's a link to the HttpPost Documentation: http://developer.android.com/reference/org/apache/http/client/methods/HttpPost.html
Hope this helps, this is a good way to get you started communicating with external MySQL databases within an Android application.
I have used javax.jdo.Query like here JDO for Google App Engine: escaping quotes. Yet, my query string with single quote (') keep getting exploded.
Query query = pm.newQuery("select from " + Book.class.getName() + " where mArtist== '"+ artist + "' && mTitle=='" + title + "'");
Here is the exception
javax.jdo.JDOUserException: Portion of expression could not be parsed: 't Give Up'
org.datanucleus.store.query.QueryCompilerSyntaxException: Portion of expression could not be parsed: 't Give Up'
Here is this query.toString()
SELECT FROM com.example.Book WHERE mArtist== 'Famous Writer' && mTitle=='We Won''t Give Up'
Yeh, I have even escaped the single quote(') with double single quote per appengine docs
a str literal, as a single-quoted string. Single-quote characters in the string must be escaped as ''. For example: 'Joe''s Diner'
Building a query by string concatenation is almost always a risky thing to do, even when SQL Injection attacks aren't possible. (They aren't with GAE.)
See http://code.google.com/appengine/docs/java/datastore/jdo/queries.html#Introducing_Queries and note the bit on "parameter substitution".
The example code in the document only cover a single parameter substitution. Here is a bit more.
Query query = pm.newQuery(Book.class);
query.setFilter("mArtist == artist && mTitle == title");
query.declareParameters("String artist,String title");
List<Book> list = (List<Book>) query.execute("Famous Writer","We Won't Give Up");
Some SO questions worth reading :
How to dynamically build JDO Queries on multiple parameters
Google Datastore problem with query on *User* type