How to read blob data from sqlite and show it - java

I have downloaded a little sqlite database file with a few words and its definitions to learn making dictionaries. And its definitions are stored in blob type. How can I read it and show its definition. I do not know what exactly is stored in blob table. I tried these :
cursor = database.rawQuery("select body from items A inner join items_info B on A.id = B.id where B.id = '" + id + "';" , null);
while (c.moveToNext()){
byte[] blob = c.getBlob(0);
}
And it got lots of various symbols with numbers and letters.
Then I converted it to string using
string = new String(blob, "UTF-8");
It gave me another result but not I want.
How can I get that blob data and show it?
Here is my db file

try SELECT hex(body) ....
then you would get a hexadecimal String.

I had the same problem, a column that I stock it as an image and i tried to show it, then I found a tutorial my much help I recommend you to see this tutorial how to write and read blob data.

Related

Android save cursor/query results to sqlite DB file

I have a method that queries a SQL table and saves the subset to a CSV file:
public void exportSQL(File outputFile, String c1) throws SQLException, IOException {
csvWrite = new CSVWriter(new FileWriter(outputFile));
curCSV = db.rawQuery("SELECT * FROM " + TABLE_NAME + " WHERE col1 = '" + c1 + "'", null);
csvWrite.writeNext(curCSV.getColumnNames());
while (curCSV.moveToNext()) {
String arrStr[] = {curCSV.getString(0), curCSV.getString(1), curCSV.getString(2),
curCSV.getString(3), curCSV.getString(4), curCSV.getString(5),
curCSV.getString(6), curCSV.getString(7), curCSV.getString(8)};
csvWrite.writeNext(arrStr);
}
csvWrite.close();
curCSV.close();
}
This works, however, I'd like to also save this query/subset as a sqlite (.db) file.
I've seen a number of questions about copying the entire database to another SQLite file, but haven't found anything containing a method for saving out only a subset of a table. In other words, I want to query a table to get a cursor, and then write the contents of that query/cursor to a .db file
Whats the correct way to do this in Java/Android?
There are a number of related questions on this, but they don't seem to cover this specific case. For example:
Copying data from one SQLite database to another. That question is about copying a table from one database to another (existing) database. Whereas I'm interested in querying/subsetting a table and saving that subset to a new (non-existing) database file
How to write a database to a text file in android. There are a number of questions like this one about saving the database to a text file, but I'd like my saved file to be a sqlite .db file, and to only contain my specific query results in a new table
I don't think you can simply save a query/subset, as a DB file that would be usable as a SQLite DB file, as a DB file holds other information e.g. it's master table.
What you could perhaps do is create a new, differently named empty database and then create the respective tables and populate them with the relevant data and finally save the new DB file.
An alternative could be to copy the DB file, open the copy as a database and then remove the components (rows tables) that you don't require to leave you with a copy with only the subset you require.
A third could be to make a copy of the original, whittle down the original, save a copy and then restore from the 1st copy.

how to write raw play queries for a table which is not mapped to an entity

I am using play framework for the first time and I need to link objects of the same type. In order to do so I have added a self referencing many to many relationship like this:
#ManyToMany(cascade=CascadeType.ALL)
#JoinTable(name="journal_predecessor", joinColumns={#JoinColumn(name="journal_id")}, inverseJoinColumns={#JoinColumn(name="predecessor_id")})
public List<Journal> journalPredecessor = new ArrayList<Journal>();
I obtain the table journal_predecessor which contains the two columns: journal_id and predecessor_id, both being FKs pointing to the primary key of the table journal.
My question is how can I query this table using raw queries if I am using H2 in-memory database. thanks!
Actually it was very easy. I just needed to create an instance of SqlQuery to create a raw query:
SqlQuery rawQuery = Ebean.createSqlQuery("SELECT journal_id from journal_predecessor where journal_id=" + successorId + " AND predecessor_id=" + predecessorId);
And because i just needed to check weather a row exists or not, I find the size of the set of the results returned by the query:
Set<SqlRow> sqlRow = rawQuery.findSet();
int rowExists = sqlRow.size();

Display data from Database in ListView

So I've been reading the Android Developer docs and have spent the last few hours reading tutorials online and have downloaded a few samples. Some of them compile, some don't.
The ones that compile use the SQLLiteDatabase in different ways than other samples I downloaded. I'm now totally confused. I was following along with the Training docs on http://developer.android.com/guide/topics/data/data-storage.html#db until I got half way down the page where it just stopped, and said that we can checkout the Note Pad sample. But the Notepad sample uses different code than what I had just read in the docs.
My scenario:
Display ListView that pulls data from SQLiteDatabase in MainActivity.xml
If user presses 'Add entry' button in AddEntryActivity.xml, add the entry to the database
If user presses 'Delete entry' button in DeleteEntryActivity.xml, delete the entry in the database.
So it's pretty simple stuff which I could do in just a couple minutes in C# but I'm new to android and I have absolutely no idea where to start. I started with the documentation, but all it does it go about half way and then refers you to the sample which is just more confusing since it uses different code.
How can I achieve this?
Use SQLiteDatabase class for this
SQLiteDatabase db = openOrCreateDatabase("Database_Name", MODE_PRIVATE, null);
//Create Table
String strsql = "CREATE TABLE IF NOT EXISTS TableName(Name VARCHAR(30),id INT(15) unique) ";
db.execSQL(strsql);
you can fire query as you do in MYSQL(INSERT,UPDATE,DELETE) using db.execSQL()
To Retrive data you can use this
strsql = "SELECT * FROM TableName ";
Cursor c = db.rawQuery(strsql, null);
int count = c.getCount();
c.moveToFirst();
while (k >= 0) {
ListviewContent.add(c.getString(c.getColumnIndex("Name")));
setListAdapter(new ListViewAdapter(this));
c.moveToNext();
k--;
}
//you can set retrived data to list view as shown above.

How to display a database columns using CRUD in play framework?

I want to display the data of a postgresql database using the CRUD in the play framework; I looked for any examples to get idea which I didn't find after a long time of searching in google. Someone help me with this if you can or post a valid link regarding this. Thanks in advance!
I use, Play 1.2.5, java and postgresql.
I assume you want to do this in your application code in runtime.
You can execute query using DB plugin to search DB metadata using native PostgreSQL queries.
Here's an example how to get column names of my system DOCUMENT table:
List<String> columns = new ArrayList<>();
ResultSet result = DB.executeQuery("select column_name from INFORMATION_SCHEMA.COLUMNS where table_name = 'DOCUMENT';");
while(result.next()) {
String column = result.getString(1);
columns.add(column);
}
This note that code is somewhat simplified and you should use prepared statements if anything in this query will be inserted from data that user or any other system entered.
Use DB.getConnection().prepareStatement() to get PreparedStatement instance.

What is the best way to import an XML string into a SQL Server table

I am working with a 3rd product called JPOS and it has an XMLPackager whereby I get a string from this packager that contains a record in an XML format such as:
<MACHINE><B000>STRING_VALUE</B000><B002>STRING_VALUE</B002><B003>STRING_VALUE</B003><B004>STRING_VALUE</B004><B007>STRING_VALUE</B007><B011>STRING_VALUE</B011><B012>STRING_VALUE</B012><B013>STRING_VALUE</B013><B015>STRING_VALUE</B015><B018>STRING_VALUE</B018><B028>STRING_VALUE</B028><B032>STRING_VALUE</B032><B035>STRING_VALUE</B035><B037>STRING_VALUE</B037><B039>STRING_VALUE</B039><B041>STRING_VALUE</B041><B043>STRING_VALUE</B043><B048>STRING_VALUE</B048><B049>STRING_VALUE</B049><B058>STRING_VALUE</B058><B061>STRING_VALUE</B061><B063>STRING_VALUE</B063><B127>STRING_VALUE</B127></MACHINE>
I have a SQL server table that contains a column for each of the listed. Not that it matters but I could potentially have thru defined with specific STRING_VALUEs. I'm not sure what is the best way to go about this in Java. My understanding is that SQL Server can take an XML string (not document) and do an insert. Is it best to parse each value and then put into a list that populate each value into? This is the first time I've used an XML file and therefore trying to get some help/direction.
Thanks.
Sorry, one of my colleagues was able to help and provide a quick answer. I'll try it from my Java code and it looks like it should work great. Thanks anyway.
Here is the SP that she created whereby I can pass in my XML string and bit value:
CREATE PROCEDURE [dbo].[sbssp_InsertArchivedMessages]
(
#doc varchar(max),
#fromTo bit
)
AS
BEGIN
DECLARE #idoc int, #lastId int
EXEC sp_xml_preparedocument #idoc OUTPUT, #doc
INSERT INTO [dbo].[tblArchivedMessages]
SELECT * FROM OPENXML(#idoc, '/MACHINE', 2) WITH [dbo].[tblArchivedMessages]
SET #lastId = (SELECT IDENT_CURRENT('tblArchivedMessages'))
UPDATE [dbo].[tblArchivedMessages]
SET FromToMach = #fromTo
WHERE ID = #lastId
END
GO
Regards.

Categories