SqLite installation with blackberry JDE - sqlite

I have installed Blackberry JDE and Eclipse. I want to create a SqLite database for my application. Should I install SqLite separately or does it come with BlackBerry JDE?

There is nothing to install separate for sqlite database. You have to create it programmatically and have to work with it. Use this.
Creating Database in SD Card :
Public void CreateDatabase()
{
Database d;
try
{
URI myURI = URI.create("file:///SDCard/Databases/" +"Test.db");
d = DatabaseFactory.create(myURI);
d.close();
add(new RichTextField("DB created successfully"));
}
catch ( Exception e )
{
System.out.println( e.getMessage() );
e.printStackTrace();
add(new RichTextField("Error: "+e.toString()));
}
}
Creating Table in Database:
Public void CreateTable()
{
Database d;
try
{
URI myURI = URI.create("file:///SDCard/Databases/"+"Test.db");
d = DatabaseFactory.open(myURI);
Statement st = d.createStatement( "CREATE TABLE 'testtable' ( " +"'id' INTEGER, " +"'name' TEXT ");
st.prepare();
st.execute();
st.close();
d.close();
add(new RichTextField("Table created successfully"));
}
catch ( Exception e )
{
System.out.println( e.getMessage() );
e.printStackTrace();
add(new RichTextField("Error: "+e.toString()));
}
}
Inserting data’s in Table:
Public void InsertData ()
{
Database d;
try
{
URI myURI = URI.create("file:///SDCard/Databases/" +"Test.db");
d = DatabaseFactory.open(myURI);
Statement st = d.createStatement("INSERT INTO testtable(id,name) " + "VALUES (1,’Arun’)");
st.prepare();
st.execute();
st.close();
d.close();
add(new RichTextField("Values Inserted"));
}
catch ( Exception e )
{
System.out.println( e.getMessage() );
e.printStackTrace();
add(new RichTextField("Error: "+e.toString()));
}
}
Retrieving Values from Database:
Public void RetriveValues()
{
Database d;
try
{
URI myURI = URI.create("file:///SDCard/Databases/" +"Test.db");
d = DatabaseFactory.open(myURI);
Statement st = d.createStatement("SELECT id,name FROM testtable");
st.prepare();
net.rim.device.api.database.Cursor c = st.getCursor();
Row r;
int i = 0;
while(c.next())
{
r = c.getRow();
i++;
add(new RichTextField(i + ". ID = " + r.getInteger(0)
+ " , "
+". Name = " + r.getString(1)));
}
if (i==0)
{
add(new RichTextField("No data in the table."));
}
st.close();
d.close();
}
catch ( Exception e )
{
System.out.println( e.getMessage() );
e.printStackTrace();
add(new RichTextField("Error: "+e.toString()));
}
}

Related

Write data from Derby to JavaFX TableView

I'm new to JavaDb/Derby.I'm migrating a project from MySQL to Derby (Project made with JavaFX).I have created an Embedded Db under NetBeans. GUI has Serial Number field (textfield), Name field (textfield), ImageView and TableView (columns with respective data). Below is the java code for connecting with Derby.
public static Connection ConnectionDb() {
try{
String url = "jdbc:derby:Test_JavaDb/webdb;create=true";
String user = "root";
String password = "root";
String driver = "org.apache.derby.jdbc.EmbeddedDriver";
Class.forName(driver).newInstance();
Connection conn = DriverManager.getConnection(url, user, password);
if (conn != null) {
System.out.println("Connected to database #1");
}
return conn;
}catch(Exception e){
JOptionPane.showMessageDialog(null,e);
}
return null;
}
//BELOW METHOD IS LINKED TO A BUTTON FOR LOADING TABLE
#FXML public void LoadTable(){
data.clear();
try{
conn = lrconn.ConnectionDb();
String sql = "select * from TEST";
pst = conn.prepareStatement(sql);
rs = pst.executeQuery();
while(rs.next()){
data.add(new TestPOJO(
rs.getString(1),
rs.getString(2),
rs.getString(3)));
Table.setItems(data);
}
pst.close();
rs.close();
}catch(Exception e1){
}
Table.setOnMouseClicked((MouseEvent me) -> {
try {
conn = lrconn.ConnectionDb();
TestPOJO user = (TestPOJO) Table.getSelectionModel().getSelectedItem();
String sql = "select * from TEST where SLNO =?";
pst = conn.prepareStatement(sql);
pst.setString(1, user.getSLNO());
rs = pst.executeQuery();
while (rs.next()) {
slnoField.setText(rs.getString(1));
nameField.setText(rs.getString(2));
try (InputStream is = rs.getBinaryStream(3)) {
OutputStream os = new FileOutputStream(new File("photo1.jpg"));
byte[] content = new byte[1024];
int size = 0;
while((size= is.read(content))!=-1){
os.write(content,0,size);
}
os.close();
} catch (IOException ex) {
Logger.getLogger(FXMLDocumentController.class.getName()).log(Level.SEVERE, null, ex);
}
image1 = new Image("file:photo1.jpg");
imgvw.setImage(image1);
rs.close();
pst.close();
}catch (SQLException ex) {
Logger.getLogger(FXMLDocumentController.class.getName()).log(Level.SEVERE, null, ex);
}
});
Table.setOnKeyReleased((KeyEvent e) -> {
if(e.getCode()== KeyCode.UP || e.getCode() == KeyCode.DOWN){
try {
TestPOJO user = (TestPOJO) Table.getSelectionModel().getSelectedItem();
String sql = "select * from TEST where SLNO =?";
pst = conn.prepareStatement(sql);
pst.setString(1, user.getSLNO());
rs = pst.executeQuery();
while (rs.next()) {
slnoField.setText(rs.getString(1));
nameField.setText(rs.getString(2));
try (InputStream is = rs.getBinaryStream(3)) {
OutputStream os = new FileOutputStream(new File("photo1.jpg"));
byte[] content = new byte[1024];
int size = 0;
while((size= is.read(content))!=-1){
os.write(content,0,size);
}os.close();
}
image1 = new Image("file:photo1.jpg");
imgvw.setImage(image1);
}}catch (FileNotFoundException ex) {
Logger.getLogger(FXMLDocumentController.class.getName()).log(Level.SEVERE, null, ex);
} catch (IOException | SQLException ex) {
Logger.getLogger(FXMLDocumentController.class.getName()).log(Level.SEVERE, null, ex);
}
}
});
}
The connection works as I get the output "Connected to database #1" on executing code (Clicking on LOAD TABLE BUTTON). But GUI table does not get updated with data from the Embedded Database. Please help.

SQLite test if record exists

I am struggling with testing if there is specific data in my SQLite database.
The method accepts a subject code, person id, and a table name. I am 100% sure those 3 things are correct.
What this should do is try to select a record. If the record can be selected return -1, otherwise return 0.
My problem is the datareader does not seem to be reading any records, when there is records in my database.
public int TestIfExists(string subID, string personID, string table)
{
_sqlConnection = new SQLiteConnection(_conStr);
bool dataRead = false;
int rc = 0;
try
{
string selectQuery = "SELECT * FROM " + table + " WHERE PersonID = '" +
personID + "' AND SubjectCode = '" + subID + "'";
_sqlConnection.Open();
SQLiteCommand sqlCommand = new SQLiteCommand(selectQuery, _sqlConnection);
IDataReader idr = sqlCommand.ExecuteReader();
dataRead = idr.Read();
if (dataRead == true)
{
rc = -1;
}//end if
else
{
rc = 0;
}//end else
idr.Close(); // Closed IDataReader
}//end try
catch (SQLiteException sqlEx) // Catch SQLiteException
{
MessageBox.Show(sqlEx.ToString());
throw new DataStoreError(sqlEx.Message);
}//end catch
catch (Exception ex)
{
throw ex;
}//end catch
finally
{
_sqlConnection.Close();
}//end finally
return rc; //Single return
}
When you are trying to see if it exists or no, you can do a
SELECT Count(*) FROM Table WHERE (...)
and this way 0 would means doesn't exists, other wise yes.

Datatype mismatch for blob type blackberry

I have an exception that Datatype mismatch in this line
byte[] _data = (byte[])row.getBlobBytes(1);
and in the table I have the type of column 2 is BLOB.
public static UrlRsc getContentUrl(String name) {
UrlRsc elementRsc = null;
try {
Statement statement = DB
.createStatement("SELECT * FROM table where"
+ " Name='"
+ name + "'");
statement.prepare();
Cursor cursor = statement.getCursor();
Row row;
while (cursor.next()) {
row = cursor.getRow();
byte[]_data;
_data = row.getBlobBytes(1);
}
statement.close();
cursor.close();
} catch (DatabaseException dbe) {
System.out.println(dbe.toString());
} catch (DataTypeException dte) {
System.out.println(dte.toString());
}
return elementRsc;
}
Can any one help me ?
Hi i am using following code for save image in my local database and i got success. i just posted my 3 methods
Note: When i am inserting image into data base i changed that image in byte array then only i can save into that table
1)Table creation 2) table insertion 3)image retrieving from table
ContactImage_table creation
public ContactImageTableCreation(){
try{
Statement stmt=DATABASE.createStatement("create table if not exists 'ContactImage_table'(ID 'TEXT',image 'blob',NodeId 'TEXT')");
stmt.prepare();
stmt.execute();
stmt.close();
}catch(Exception e){
System.out.println(e.getMessage());
}
}
Insert data into ContactImage_table
public void ContactImageTableInsertion(){
try{
Statement st=DATABASE.createStatement("insert into ContactImage_table (ID,Image,NodeId)values(?,?,?)");
st.prepare();
st.bind(1, "101");
st.bind(2, BYTE_ARRY);
st.bind(3,"103");
st.execute();
st.close();
}catch (Exception e) {
System.out.println(e.getMessage());
}
}
Retrieving data from ContactImage_table
public ContactImageTableDataRetriving(){
try{
Statement st=DATABASE.createStatement("select * from ContactImage_table");
st.prepare();
Cursor c=st.getCursor();
Row r;
int i=0;
while(c.next()){
r=c.getRow();
i++;
// ContactImageObject is a wrapper class for data handling
contactImageObj=new ContactImageObject();
contactImageObj.setId(r.getString(0));
byte[] decoded=r.getBlobBytes(1);
EncodedImage fullImage = EncodedImage.createEncodedImage(decoded, 0, decoded.length);
Bitmap b=fullImage.getBitmap();
contactImageObj.setImage(b);
// System.out.println("Successfully retrived");
if(i==0){
// System.out.println("No Records");
}
}
st.close();
}catch (Exception e) {
// System.out.println(e.getMessage());
}
}
just cross check your code with this code snippet hope you will get resolve all the best

SQLite keep expanding

I'm new to the blackberry development and to this site. right now, i'm working on an app that retrieve data from a json service. In my app I should parse the data into a database and save it in four tables. I already parsed the data and I was successful able to create the database and add the first and the second tables.
The problem that I'm facing right now is, the second table in my data base keep expanding. I checked the database in the sql browser and I discovered that everytime I click on the app icon it adds the 700 rows to the table again.(ex. 700 becomes 1400) .
(only to the second table, the first table works so fine).
Thank you in advance
This is my code:
public void parseJSONResponceInBB(String jsonInStrFormat)
{
try {
JSONObject json = newJSONObject(jsonInStrFormat);
JSONArray jArray = json.getJSONArray("tables");
for (inti = 0; i < jArray.length(); i++) {
//Iterate through json array
JSONObject j = jArray.getJSONObject(i);
if (j.has("Managers")) {
add(new LabelField("Managers has been added to the database"));
JSONArray j2 = j.getJSONArray("Managers");
for (intk = 0; k < j2.length(); ++k) {
JSONObject MangersDetails = j2.getJSONObject(k);
if (MangersDetails.has("fName")) {
try {
URI myURI =
URI.create
("file:///SDCard/Databases/SQLite_Guide/"
+ "MyTestDatabase.db");
d = DatabaseFactory.openOrCreate(myURI);
Statement st =
d.createStatement
("CREATE TABLE Managers ( "
+ "fName TEXT, " +
"lName TEXT, " + "ID TEXT," + "Type TEXT )");
st.prepare();
st.execute();
st.close();
d.close();
}
catch(Exception e) {
System.out.println(e.getMessage());
e.printStackTrace();
}
try {
URI myURI =
URI.create
("file:///SDCard/Databases/SQLite_Guide/"
+ "MyTestDatabase.db");
d = DatabaseFactory.open(myURI);
Statement st =
d.createStatement
("INSERT INTO Managers(fName, lName, ID, Type) "
+ "VALUES (?,?,?,?)");
st.prepare();
for (intx = 0; x < j2.length(); x++) {
JSONObject F = j2.getJSONObject(x);
//add(new LabelField ("f"));
st.bind(1, F.getString("fName"));
st.bind(2, F.getString("lName"));
st.bind(3, F.getString("ID"));
st.bind(4, F.getString("Type"));
st.execute();
st.reset();
}
d.close();
}
catch(Exception e) {
System.out.println(e.getMessage());
e.printStackTrace();
}
}
}
}
}
}
catch(JSONException e) {
e.printStackTrace();
}
}
//Owners method
public voidparseJSONResponceInBB1(String jsonInStrFormat)
{
try {
JSONObject json = newJSONObject(jsonInStrFormat);
JSONArray jArray = json.getJSONArray("tables");
for (inti = 0; i < jArray.length(); i++) {
//Iterate through json array
JSONObject j = jArray.getJSONObject(i);
if (j.has("Owners")) {
add(new LabelField("Owners has been added to the database"));
JSONArray j2 = j.getJSONArray("Owners");
for (intk = 0; k < j2.length(); ++k) {
JSONObject OwnersDetails = j2.getJSONObject(k);
if (OwnersDetails.has("fName")) {
try {
Statement st =
d.createStatement
("CREATE TABLE Owners ( "
+ "fName TEXT, " +
"lName TEXT, " + "ID TEXT," + "Type TEXT )");
st.prepare();
st.execute();
st.close();
d.close();
}
catch(Exception e) {
System.out.println(e.getMessage());
e.printStackTrace();
}
try {
Statement st =
d.createStatement
("INSERT INTO Owners(fName, lName, ID, Type) "
+ "VALUES (?,?,?,?)");
st.prepare();
for (intx = 0; x < j2.length(); x++) {
JSONObject F = j2.getJSONObject(x);
//add(new LabelField ("f"));
st.bind(1, F.getString("fName"));
st.bind(2, F.getString("lName"));
st.bind(3, F.getString("ID"));
st.bind(4, F.getString("Type"));
st.execute();
st.reset();
}
d.close();
}
catch(Exception e) {
System.out.println(e.getMessage());
e.printStackTrace();
}
}
}
}
}
}
catch(JSONException e) {
e.printStackTrace();
}
}
It depends on what your goals are here. If you want to replace the data in the database each time the json query runs, you should add a sqlite command to remove all the existing rows with the newly fetched ones coming in via JSON.
If you just want to keep certain types of records unique, you should add an index to the sqlite table. The 'ID' column is a likely candidate for this. You'll have to do some experiments to make sure a conflict is handled correctly - it may abort the entire transaction. "INSERT OR REPLACE" is useful in that situation.

How to insert an array of String in SQLite database in blackberry

I have a Database Manager class which is creating the SQLite Database.Now from another class, i am creating the instance of that class. Now how can i insert an array of string in the Database?
My Database Manager class code is like below:
public class DatabaseManager
{
public Database sqliteDb = null;
public DatabaseManager()
{
try
{
URI myURI = URI.create("/SDCard/databases/itemdb.db");
Database sqliteDb = DatabaseFactory.openOrCreate(myURI);
sqliteDb.close();
sqliteDb = DatabaseFactory.open(myURI);
Statement statement = sqliteDb.createStatement("CREATE TABLE if not exists SelectedItem (Name TEXT, Quantity TEXT)");
statement.prepare();
statement.execute();
statement.close();
}
catch (Exception e)
{
e.printStackTrace();
}
finally
{
try
{
if(sqliteDb!=null)
{
sqliteDb.close();
}
}
catch (Exception e)
{
e.printStackTrace();
}
}
}
public static void insertValues(String tableName, Hashtable ht)
{
try
{
Logger.out("Grocery", "it is comin here");
URI myURI = null;
try
{
myURI = URI.create("/SDCard/databases/itemdb.db");
}
catch (IllegalArgumentException e)
{
e.printStackTrace();
}
catch (MalformedURIException e)
{
e.printStackTrace();
}
Database sqliteDb = DatabaseFactory.openOrCreate(myURI);
sqliteDb.close();
sqliteDb = DatabaseFactory.open(myURI);
Statement dbStatement = sqliteDb.createStatement("INSERT INTO SelectedItem(Name,Quantity) " + "VALUES (?,?)");
Enumeration itemName = ht.keys();
Enumeration itemQty = ht.elements();
while(itemName.hasMoreElements())
{
Logger.out("Grocery", "more items");
String strName = itemName.nextElement().toString();
String strQty = itemQty.nextElement().toString();
Logger.out("Grocery", "name:" + " " + strName);
Logger.out("Grocery", "QTY:" + " " + strQty);
dbStatement.bind(1, strName);
dbStatement.bind(2, strQty);
Logger.out("Grocery", "Binded:::::::::");
dbStatement.execute();
dbStatement.reset();
Logger.out("Grocery", "Executed:::::::::");
}
dbStatement.close();
}
catch (DatabaseException e)
{
e.printStackTrace();
}
}
public void closeDb()
{
try
{
sqliteDb.close();
}
catch (DatabaseIOException e)
{
e.printStackTrace();
}
}
}
Now i am taking the name and quantity as a hash table. And in my main class, when i am pressing the button i am inserting the values in the database like below:
dbManager = new DatabaseManager();
dbManager.insertValues("SelectedItem", htItem);
Try this as following when ever you want to use another class method as globle then just declare it as static . genaral query for multiple row insertion is
INSERT INTO 'tablename' SELECT 'data1' AS 'column1', 'data2' AS
'column2' UNION SELECT 'data3', 'data4' UNION SELECT 'data5', 'data6'
UNION SELECT 'data7', 'data8'
import net.rim.device.api.ui.Field;
import net.rim.device.api.ui.FieldChangeListener;
import net.rim.device.api.ui.UiApplication;
import net.rim.device.api.ui.component.ButtonField;
import net.rim.device.api.ui.component.LabelField;
import net.rim.device.api.ui.container.MainScreen;
public class SampleDatabase extends UiApplication
{
LabelField test;
String names[];
int ages[];
MainScreen screen = new MainScreen();
public static void main(String[] args)
{
SampleDatabase theApp = new SampleDatabase();
theApp.enterEventDispatcher();
}
public SampleDatabase()
{
ButtonField btn=new ButtonField("Click");
names=new String[10];
ages=new int[10];
for(int i=0;i<10;i++)
{
names[i]="Govind"+i;
ages[i]=i;
}
btn.setChangeListener(new FieldChangeListener() {
public void fieldChanged(Field field, int context) {
synchronized (UiApplication.getEventLock()) {
databaseOperations.DatabaseManager();
databaseOperations.InsertDatabaseManager(names,ages);
}
}
});
screen.add(btn);
pushScreen(screen);
}
}
This is another class named as "databaseOperations.java"
import net.rim.device.api.database.Database;
import net.rim.device.api.database.DatabaseFactory;
import net.rim.device.api.database.Statement;
import net.rim.device.api.io.URI;
public class databaseOperations {
public static void DatabaseManager()
{
Database d=null;
try {
URI uri = URI.create("file:///SDCard/Databases/SQLite_Guide/" +
"MyTestDatabase.db");
d = DatabaseFactory.openOrCreate(uri);
d.close();
d = DatabaseFactory.open(uri);
Statement s = d.createStatement( "CREATE TABLE if not exists 'People' ( " +
"'Name' TEXT, " +
"'Age' INTEGER )");
s.prepare();
s.execute();
s.close();
}
catch(Exception e)
{
e.printStackTrace();
}
finally
{
try {
if(d!=null)
{
d.close();
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
public static void InsertDatabaseManager(String[] names,int ages[])
{
Database d=null;
try {
URI uri = URI.create("file:///SDCard/Databases/SQLite_Guide/" +
"MyTestDatabase.db");
d = DatabaseFactory.openOrCreate(uri);
d.close();
d = DatabaseFactory.open(uri);
String query="INSERT INTO 'People' SELECT '"+names[0]+"' AS 'Name', "+ages[0]+" AS 'Age'";
String query2="";
for(int i=1;i<names.length;i++)
{
query2=query2+" UNION SELECT '"+names[i]+"', "+ages[i];
}
System.out.println(query+query2);
Statement s = d.createStatement(query+query2);
s.prepare();
s.execute();
s.close();
}
catch(Exception e)
{
e.printStackTrace();
}
finally
{
try {
if(d!=null)
{
d.close();
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}

Resources