0

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);
2
  • array of strings means do you want to insert multiple names with age values? Commented Feb 17, 2012 at 4:11
  • Yes..but i want to insert from another class, not from DatabaseManager class.. Commented Feb 17, 2012 at 5:04

1 Answer 1

1

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();
        }
       }
      }
}
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks for your reply. I edited and added my latest code. But still it is not inserting the values in database..

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.