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

孤街醉人 提交于 2019-12-25 03:29:19

问题


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);

回答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();
        }
       }
      }
}


来源:https://stackoverflow.com/questions/9313974/how-to-insert-an-array-of-string-in-sqlite-database-in-blackberry

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!