How to verify an attribute whether it present in table or not without using scan in dynamodb?
In my usecase, From client side, The customer request with their Customer_id for knowing the values of the product. In server side, have to check whether the entered customer_id already present in DynamoDB table or not. If not, have to make a new entry.
How can I implement this case without using SCAN operation to the table?
It sounds to me that you want to do a conditional PutItem on this table: put the item into the table if there is not another item with the same customer_id. This is easy enough to do because the customer_id is the hash key of the table. From the PutItem documentation:
Note
To prevent a new item from replacing an existing item, use a conditional put operation with ComparisonOperator set to NULL for the
primary key attribute, or attributes.
Here is a quick example I coded up using the Dynamo DB document API in the Java SDK and running against DynamoDB Local:
import com.amazonaws.auth.BasicAWSCredentials;
import com.amazonaws.services.dynamodbv2.AmazonDynamoDB;
import com.amazonaws.services.dynamodbv2.AmazonDynamoDBClient;
import com.amazonaws.services.dynamodbv2.document.DynamoDB;
import com.amazonaws.services.dynamodbv2.document.Expected;
import com.amazonaws.services.dynamodbv2.document.Item;
import com.amazonaws.services.dynamodbv2.document.Table;
import com.amazonaws.services.dynamodbv2.model.AttributeDefinition;
import com.amazonaws.services.dynamodbv2.model.ConditionalCheckFailedException;
import com.amazonaws.services.dynamodbv2.model.CreateTableRequest;
import com.amazonaws.services.dynamodbv2.model.KeySchemaElement;
import com.amazonaws.services.dynamodbv2.model.KeyType;
import com.amazonaws.services.dynamodbv2.model.ProvisionedThroughput;
import com.amazonaws.services.dynamodbv2.model.ScalarAttributeType;
import com.amazonaws.services.dynamodbv2.util.Tables;
public class StackOverflow {
private static final String EXAMPLE_TABLE_NAME = "example_table";
public static void main(String[] args) {
AmazonDynamoDB client = new AmazonDynamoDBClient(new BasicAWSCredentials("accessKey", "secretKey"));
client.setEndpoint("http://localhost:4000");
DynamoDB dynamoDB = new DynamoDB(client);
if (Tables.doesTableExist(client, "example_table")) client.deleteTable(EXAMPLE_TABLE_NAME);
// Create table with hash key 'customer_id'
CreateTableRequest createTableRequest = new CreateTableRequest();
createTableRequest.withTableName(EXAMPLE_TABLE_NAME);
createTableRequest.withKeySchema(new KeySchemaElement("customer_id", KeyType.HASH));
createTableRequest.withAttributeDefinitions(new AttributeDefinition("customer_id", ScalarAttributeType.S));
createTableRequest.withProvisionedThroughput(new ProvisionedThroughput(15l, 15l));
dynamoDB.createTable(createTableRequest);
Tables.waitForTableToBecomeActive(client, EXAMPLE_TABLE_NAME);
Table exampleTable = dynamoDB.getTable(EXAMPLE_TABLE_NAME);
exampleTable.putItem(new Item()
.withPrimaryKey("customer_id", "ABCD")
.withString("customer_name", "Jim")
.withString("customer_email", "jim#gmail.com"));
System.out.println("After Jim:");
exampleTable.scan()
.forEach(System.out::println);
System.out.println();
try {
exampleTable.putItem(new Item()
.withPrimaryKey("customer_id", "EFGH")
.withString("customer_name", "Garret")
.withString("customer_email", "garret#gmail.com"), new Expected("customer_id").notExist());
} catch (ConditionalCheckFailedException e) {
System.out.println("Conditional check failed!");
}
System.out.println("After Garret:");
exampleTable.scan()
.forEach(System.out::println);
System.out.println();
try {
exampleTable.putItem(new Item()
.withPrimaryKey("customer_id", "ABCD")
.withString("customer_name", "Bob")
.withString("customer_email", "bob#gmail.com"), new Expected("customer_id").notExist());
} catch (ConditionalCheckFailedException e) {
System.out.println("Conditional check failed!");
}
System.out.println("After Bob:");
exampleTable.scan()
.forEach(System.out::println);
}
}
Output:
After Jim:
{ Item: {customer_email=jim#gmail.com, customer_name=Jim, customer_id=ABCD} }
After Garret:
{ Item: {customer_email=garret#gmail.com, customer_name=Garret, customer_id=EFGH} }
{ Item: {customer_email=jim#gmail.com, customer_name=Jim, customer_id=ABCD} }
Conditional check failed!
After Bob:
{ Item: {customer_email=garret#gmail.com, customer_name=Garret, customer_id=EFGH} }
{ Item: {customer_email=jim#gmail.com, customer_name=Jim, customer_id=ABCD} }
Related
I have a case where I need to dynamically retrieve the results of a specific book. I would like to retrieve that specific book by using its ISBN number (highlighted in bold below). This is how my database looks like:
{
"results" :
{
"key1" : {
"Character_Depth" : 4,
"Dialogue" : 4,
"Plot" : 5,
"Theme" : 3,
"Writing_Style" : 3,
"bookName" : "Ionic",
"isbnNumber" : "0123456789012"
},
"key2" : {
"Character_Depth" : 4,
"Dialogue" : 4,
"Plot" : 4,
"Theme" : 2,
"Writing_Style" : 4,
"bookName" : "Justin",
"isbnNumber" : "036000291452"
}
}
}
Before I dive into the code, here is some important information I think you need to know. What I am trying to specifically do is use a barcode scanner to scan the ISBN number of a book. Then I would like to use that scanned ISBN number to dynamically retrieve results from that database. With that being said, I need to design my code in such a way that the barcode scanner variable is updated every single time (with each scan) to the new barcode number (already completed). Then that barcode number is fed into the query (which I still can't get to work, and is what I need help with) which retrieves a child node based on that number.
My code:
import { Component } from '#angular/core';
import { IonicPage, NavController, NavParams, AlertController } from 'ionic-angular';
import { BarcodeScanner, BarcodeScannerOptions } from '#ionic-native/barcode-scanner';
import { AngularFireAuth } from 'angularfire2/auth';
import { AngularFireDatabase, AngularFireList } from 'angularfire2/database';
import { HomePage } from '../home/home';
import { Observable } from 'rxjs/Observable';
#IonicPage()
#Component({
selector: 'page-login',
templateUrl: 'login.html',
})
export class LoginPage {
bookResults: Observable<any[]>;
options: BarcodeScannerOptions;
results: {};
constructor(public navCtrl: NavController,
public navParams: NavParams,
private fire: AngularFireAuth,
private database: AngularFireDatabase,
private barcodeScanner: BarcodeScanner,
private alertCtrl: AlertController) {
/* ########## part of the code where I specifically need help ########## */
this.bookResults = this.database.list('results').valueChanges();
}
/* ########### Barcode scanner function */
async Scan(){
this.results = await this.barcodeScanner.scan();
console.log(this.results);
}
}
Right now, what happens is that the "this.bookResults = this.database.list('results').valueChanges();" retrieves the above database. However, I need some guidance as to how to change my query such that I can retrieve specific child nodes based on the "isbnNumber" instance of each child.
I've tried several things. More recently I've tried:
this.bookResults = this.database.list('/results', {
query: {
orderByChild: isbnNumber,
equalTo: this.results,
}
});
but that didn't work. I've tried other things such as:
this.bookResults =
this.database.list('/results/${this.results}').valueChanges();
but it hasn't worked either.
I've read various stackoverflow threads, so I wouldn't be surprised if this was marked as duplicate. I have tried following the instructions of various threads, yet I felt that the way retrieving information from the database didn't specifically apply to my current situation, as the values used to retrieve specific child nodes where hardcoded into the query. I need a dynamically changing query that adjusts itself based on the barcode scanner's results).
Please let me know if there is anything that was unclear from this post, and I'd be more than happy to help. Also, if you are interested in seeing the source code, here is a link to my github repo containing it:
https://github.com/islamaymansais/honey_scanner
(go to src -> pages -> login -> login.ts)
Thanks for taking the time to read this long post. I am a beginner , I've gone through plenty of posts but unfortunately I was not able to apply the appropriate changes due to my lack of experience with ionic.
As per the readme notes for the Angular firebase library the following should work:
constructor(public navCtrl: NavController,
public navParams: NavParams,
private fire: AngularFireAuth,
private database: AngularFireDatabase,
private barcodeScanner: BarcodeScanner,
private alertCtrl: AlertController) {
this.getData();
}
async function Scan(){
this.results = await this.barcodeScanner.scan();
console.log(this.results);
this.getData();
}
this.getData = () => {
var scanned_Barcode_Text = "";
if (Object.keys(this.results).length > 0){
if(typeof this.results['text'] != 'undefined' && this.results['text'] != ""){
scanned_Barcode_Text = this.results['text'];
}
}
this.bookResults = this.database.list('/results',
ref => (scanned_Barcode_Text != "") ? ref.orderByChild('isbnNumber').equalTo(scanned_Barcode_Text) : ref
).snapshotChanges();
}
call the getData() function in the constructor and also in the success function of the barcode scan.
The orderBy and equal to queries can only be called on the reference objects which is the second parameter(optional) of the AngularFireDatabase object. The usage is similar to the reduce function of the Array.prototype.
Hope this helps.
Try this.
let booksRef = this.firebase.database().ref("results/");
booksRef.orderByChild("isbnNumber").equalTo(scannedBarCode).on("child_added", function(data) {
console.log(data.val());
this.bookResults = data.val();
});
I am considering that you have got the barcode value already and have it in the variable scannerBarCode.
Sidenote: In my opinion, since you are querying the database on ISBN, you should use that instead of key. It will make it simple. Also try the new Cloud Firestore that has better querying features.
I'm working with DynamoDB at the moment. I want to use a conditional write to update a record if that record has a date that is older than the new record date field.
Is there a way to compare DateTime types for conditional writes? Or is it currently only for integers, strings and streams?
Thanks.
Since you mentioned you are using ISO-8601 with the String datatype, it is easy to use the comparing operators (<, <=, etc.) in your conditional expression because of the lexicographical ordering described in this answer.
Here is a quick example where I used Java 8's time and ran it against DynamoDB Local:
import com.google.common.collect.ImmutableMap;
import com.amazonaws.auth.AWSCredentials;
import com.amazonaws.auth.BasicAWSCredentials;
import com.amazonaws.services.dynamodbv2.AmazonDynamoDB;
import com.amazonaws.services.dynamodbv2.AmazonDynamoDBClient;
import com.amazonaws.services.dynamodbv2.document.DynamoDB;
import com.amazonaws.services.dynamodbv2.document.Item;
import com.amazonaws.services.dynamodbv2.document.Table;
import com.amazonaws.services.dynamodbv2.document.spec.UpdateItemSpec;
import com.amazonaws.services.dynamodbv2.model.AttributeDefinition;
import com.amazonaws.services.dynamodbv2.model.ConditionalCheckFailedException;
import com.amazonaws.services.dynamodbv2.model.CreateTableRequest;
import com.amazonaws.services.dynamodbv2.model.KeySchemaElement;
import com.amazonaws.services.dynamodbv2.model.KeyType;
import com.amazonaws.services.dynamodbv2.model.ProvisionedThroughput;
import com.amazonaws.services.dynamodbv2.model.ScalarAttributeType;
import com.amazonaws.services.dynamodbv2.util.Tables;
import java.time.Instant;
import java.time.temporal.ChronoUnit;
public class DynamoDBStackoverflow {
public static final String TABLE_NAME = "exampleTable";
private static final String HASH_KEY = "hashAttributeName";
public static void main(String[] args) {
AWSCredentials awsCredentials = new BasicAWSCredentials("key", "secret");
AmazonDynamoDB client = new AmazonDynamoDBClient(awsCredentials);
client.setEndpoint("http://localhost:4000");
DynamoDB dynamoDB = new DynamoDB(client);
if (Tables.doesTableExist(client, TABLE_NAME)) {
client.deleteTable(TABLE_NAME);
}
final CreateTableRequest createTableRequest = new CreateTableRequest()
.withTableName(TABLE_NAME)
.withKeySchema(new KeySchemaElement(HASH_KEY, KeyType.HASH))
.withAttributeDefinitions(new AttributeDefinition(HASH_KEY, ScalarAttributeType.S))
.withProvisionedThroughput(new ProvisionedThroughput(15L, 15L));
final Table table = dynamoDB.createTable(createTableRequest);
final Instant now = Instant.now();
final Instant before = now.minus(10, ChronoUnit.MINUTES).truncatedTo(ChronoUnit.MINUTES);
final Instant after = now.plus(10, ChronoUnit.MINUTES);
System.out.println("Before: " + before.toString());
System.out.println("Now: " + now.toString());
System.out.println("After: " + after.toString());
table.putItem(new Item().withPrimaryKey(HASH_KEY, "1")
.withString("dateField", before.toString()));
table.putItem(new Item().withPrimaryKey(HASH_KEY, "2")
.withString("dateField", now.toString()));
System.out.println("put items");
table.scan().forEach(System.out::println);
UpdateItemSpec updateItemSpec = new UpdateItemSpec().withPrimaryKey(HASH_KEY, "1")
.withConditionExpression("dateField < :beforeDate")
.withValueMap(ImmutableMap.of(":beforeDate", before.toString()))
.withUpdateExpression("SET dateField = :beforeDate");
try {
table.updateItem(updateItemSpec);
throw new RuntimeException();
} catch (ConditionalCheckFailedException ccfe) {
System.out.println("expected conditional write with < to fail when they are equal");
}
updateItemSpec = new UpdateItemSpec().withPrimaryKey(HASH_KEY, "2")
.withConditionExpression("dateField < :beforeDate")
.withValueMap(ImmutableMap.of(":beforeDate", before.toString()))
.withUpdateExpression("SET dateField = :beforeDate");
try {
table.updateItem(updateItemSpec);
throw new RuntimeException();
} catch (ConditionalCheckFailedException ccfe) {
System.out.println("expected conditional write with < to fail when new is before");
}
updateItemSpec = new UpdateItemSpec().withPrimaryKey(HASH_KEY, "1")
.withConditionExpression("dateField <= :beforeDate")
.withValueMap(ImmutableMap.of(":beforeDate", before.toString()))
.withUpdateExpression("SET dateField = :beforeDate");
try {
table.updateItem(updateItemSpec);
} catch (ConditionalCheckFailedException ccfe) {
System.out.println("should not happen");
throw new RuntimeException();
}
updateItemSpec = new UpdateItemSpec().withPrimaryKey(HASH_KEY, "2")
.withConditionExpression("dateField <= :afterDate")
.withValueMap(ImmutableMap.of(":afterDate", after.toString()))
.withUpdateExpression("SET dateField = :afterDate");
try {
table.updateItem(updateItemSpec);
} catch (ConditionalCheckFailedException ccfe) {
System.out.println("should not happen");
throw new RuntimeException();
}
System.out.println();
System.out.println("after all updates");
table.scan().forEach(System.out::println);
}
}
And the output:
Before: 2015-06-08T15:57:00Z
Now: 2015-06-08T16:07:08.893Z
After: 2015-06-08T16:17:08.893Z
put items
{ Item: {hashAttributeName=1, dateField=2015-06-08T15:57:00Z} }
{ Item: {hashAttributeName=2, dateField=2015-06-08T16:07:08.893Z} }
expected conditional write with < to fail when they are equal
expected conditional write with < to fail when new is before
after all updates
{ Item: {hashAttributeName=1, dateField=2015-06-08T15:57:00Z} }
{ Item: {hashAttributeName=2, dateField=2015-06-08T16:17:08.893Z} }
DynamoDB doesn't understand dates. If you save the date as long, ms/s since epoch, then you can use arithmetic <, >=, etc.
If you use a String presentation, then it all depends if you can find the right DynamoDB operator to query on two of them.
I personally use the former, thus doing it with calculus.
Say I have an enum
public enum E {A,B,C}
Is it possible to add another value, say D, by AspectJ?
After googling around, it seems that there used to be a way to hack the private static field $VALUES, then call the constructor(String, int) by reflection, but seems not working with 1.7 anymore.
Here are several links:
http://www.javaspecialists.eu/archive/Issue161.html (provided by #WimDeblauwe )
and this: http://www.jroller.com/VelkaVrana/entry/modify_enum_with_reflection
Actually, I recommend you to refactor the source code, maybe adding a collection of valid region IDs to each enumeration value. This should be straightforward enough for subsequent merging if you use Git and not some old-school SCM tool like SVN.
Maybe it would even make sense to use a dynamic data structure altogether instead of an enum if it is clear that in the future the list of commands is dynamic. But that should go into the upstream code base. I am sure the devs will accept a good patch or pull request if prepared cleanly.
Remember: Trying to avoid refactoring is usually a bad smell, a symptom of an illness, not a solution. I prefer solutions to symptomatic workarounds. Clean code rules and software craftsmanship attitude demand that.
Having said the above, now here is what you can do. It should work under JDK 7/8 and I found it on Jérôme Kehrli's blog (please be sure to add the bugfix mentioned in one of the comments below the article).
Enum extender utility:
package de.scrum_master.util;
import java.lang.reflect.AccessibleObject;
import java.lang.reflect.Array;
import java.lang.reflect.Field;
import java.lang.reflect.Modifier;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import sun.reflect.ConstructorAccessor;
import sun.reflect.FieldAccessor;
import sun.reflect.ReflectionFactory;
public class DynamicEnumExtender {
private static ReflectionFactory reflectionFactory =
ReflectionFactory.getReflectionFactory();
private static void setFailsafeFieldValue(Field field, Object target, Object value)
throws NoSuchFieldException, IllegalAccessException
{
// let's make the field accessible
field.setAccessible(true);
// next we change the modifier in the Field instance to
// not be final anymore, thus tricking reflection into
// letting us modify the static final field
Field modifiersField = Field.class.getDeclaredField("modifiers");
modifiersField.setAccessible(true);
int modifiers = modifiersField.getInt(field);
// blank out the final bit in the modifiers int
modifiers &= ~Modifier.FINAL;
modifiersField.setInt(field, modifiers);
FieldAccessor fa = reflectionFactory.newFieldAccessor(field, false);
fa.set(target, value);
}
private static void blankField(Class<?> enumClass, String fieldName)
throws NoSuchFieldException, IllegalAccessException
{
for (Field field : Class.class.getDeclaredFields()) {
if (field.getName().contains(fieldName)) {
AccessibleObject.setAccessible(new Field[] { field }, true);
setFailsafeFieldValue(field, enumClass, null);
break;
}
}
}
private static void cleanEnumCache(Class<?> enumClass)
throws NoSuchFieldException, IllegalAccessException
{
blankField(enumClass, "enumConstantDirectory"); // Sun (Oracle?!?) JDK 1.5/6
blankField(enumClass, "enumConstants"); // IBM JDK
}
private static ConstructorAccessor getConstructorAccessor(Class<?> enumClass, Class<?>[] additionalParameterTypes)
throws NoSuchMethodException
{
Class<?>[] parameterTypes = new Class[additionalParameterTypes.length + 2];
parameterTypes[0] = String.class;
parameterTypes[1] = int.class;
System.arraycopy(additionalParameterTypes, 0, parameterTypes, 2, additionalParameterTypes.length);
return reflectionFactory.newConstructorAccessor(enumClass .getDeclaredConstructor(parameterTypes));
}
private static Object makeEnum(Class<?> enumClass, String value, int ordinal, Class<?>[] additionalTypes, Object[] additionalValues)
throws Exception
{
Object[] parms = new Object[additionalValues.length + 2];
parms[0] = value;
parms[1] = Integer.valueOf(ordinal);
System.arraycopy(additionalValues, 0, parms, 2, additionalValues.length);
return enumClass.cast(getConstructorAccessor(enumClass, additionalTypes).newInstance(parms));
}
/**
* Add an enum instance to the enum class given as argument
*
* #param <T> the type of the enum (implicit)
* #param enumType the class of the enum to be modified
* #param enumName the name of the new enum instance to be added to the class
*/
#SuppressWarnings("unchecked")
public static <T extends Enum<?>> void addEnum(Class<T> enumType, String enumName) {
// 0. Sanity checks
if (!Enum.class.isAssignableFrom(enumType))
throw new RuntimeException("class " + enumType + " is not an instance of Enum");
// 1. Lookup "$VALUES" holder in enum class and get previous enum
// instances
Field valuesField = null;
Field[] fields = enumType.getDeclaredFields();
for (Field field : fields) {
if (field.getName().contains("$VALUES")) {
valuesField = field;
break;
}
}
AccessibleObject.setAccessible(new Field[] { valuesField }, true);
try {
// 2. Copy it
T[] previousValues = (T[]) valuesField.get(enumType);
List<T> values = new ArrayList<T>(Arrays.asList(previousValues));
// 3. build new enum
T newValue = (T) makeEnum(
enumType, // The target enum class
enumName, // THE NEW ENUM INSTANCE TO BE DYNAMICALLY ADDED
values.size(), new Class<?>[] {}, // could be used to pass values to the enum constuctor if needed
new Object[] {} // could be used to pass values to the enum constuctor if needed
);
// 4. add new value
values.add(newValue);
// 5. Set new values field
setFailsafeFieldValue(valuesField, null, values.toArray((T[]) Array.newInstance(enumType, 0)));
// 6. Clean enum cache
cleanEnumCache(enumType);
} catch (Exception e) {
e.printStackTrace();
throw new RuntimeException(e.getMessage(), e);
}
}
}
Sample application & enum:
package de.scrum_master.app;
/** In honour of "The Secret of Monkey Island"... ;-) */
public enum Command {
OPEN, CLOSE, PUSH, PULL, WALK_TO, PICK_UP, TALK_TO, GIVE, USE, LOOK_AT, TURN_ON, TURN_OFF
}
package de.scrum_master.app;
public class Server {
public void executeCommand(Command command) {
System.out.println("Executing command " + command);
}
}
package de.scrum_master.app;
public class Client {
private Server server;
public Client(Server server) {
this.server = server;
}
public void issueCommand(String command) {
server.executeCommand(
Command.valueOf(
command.toUpperCase().replace(' ', '_')
)
);
}
public static void main(String[] args) {
Client client = new Client(new Server());
client.issueCommand("use");
client.issueCommand("walk to");
client.issueCommand("undress");
client.issueCommand("sleep");
}
}
Console output with original enum:
Executing command USE
Executing command WALK_TO
Exception in thread "main" java.lang.IllegalArgumentException: No enum constant de.scrum_master.app.Command.UNDRESS
at java.lang.Enum.valueOf(Enum.java:236)
at de.scrum_master.app.Command.valueOf(Command.java:1)
at de.scrum_master.app.Client.issueCommand(Client.java:12)
at de.scrum_master.app.Client.main(Client.java:22)
Now you can either add an aspect with an advice executed after the enum class was loaded or just call this manually in your application before extended enum values are to be used for the first time. Here I am showing how it can be done in an aspect.
Enum extender aspect:
package de.scrum_master.aspect;
import de.scrum_master.app.Command;
import de.scrum_master.util.DynamicEnumExtender;
public aspect CommandExtender {
after() : staticinitialization(Command) {
System.out.println(thisJoinPoint);
DynamicEnumExtender.addEnum(Command.class, "UNDRESS");
DynamicEnumExtender.addEnum(Command.class, "SLEEP");
DynamicEnumExtender.addEnum(Command.class, "WAKE_UP");
DynamicEnumExtender.addEnum(Command.class, "DRESS");
}
}
Console output with extended enum:
staticinitialization(de.scrum_master.app.Command.<clinit>)
Executing command USE
Executing command WALK_TO
Executing command UNDRESS
Executing command SLEEP
Et voilà! ;-)
im running a jdbc program on Sqlite. though i change the environmental variables or define the classpath of the jar file sqlite-jdbc-3.7.2.jar, i get an error stating ClassNotFoundException: org.sqlite.JDBC... how to rectify it?
my code is`
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
public class Sample
{
public static void main(String[] args)throws ClassNotFoundException
{
// load the sqlite-JDBC driver using the current class loader
Class.forName("org.sqlite.JDBC");
Connection connection = null;
try
{
// create a database connection
connection = DriverManager.getConnection("jdbc:sqlite:sample.db");
Statement statement = connection.createStatement();
statement.setQueryTimeout(30); // set timeout to 30 sec.
statement.executeUpdate("drop table if exists person");
statement.executeUpdate("create table person (id integer, name string)");
statement.executeUpdate("insert into person values(1, 'leo')");
statement.executeUpdate("insert into person values(2, 'yui')");
ResultSet rs = statement.executeQuery("select * from person");
while(rs.next())
{
// read the result set
System.out.println("name = " + rs.getString("name"));
System.out.println("id = " + rs.getInt("id"));
}
}
catch(SQLException e)
{
// if the error message is "out of memory",
// it probably means no database file is found
System.err.println(e.getMessage());
}
finally
{
try
{
if(connection != null)
connection.close();
}
catch(SQLException e)
{
// connection close failed.
System.err.println(e);
}
}
}
}`
my jar file is sqlite-jdbc-3.7.2.jar
my class path is D:\jdk1.6.0_45\sqlite-jdbc-3.7.2.jar
my environmental variable is also the same
what should i do?
help pls
i found the solution to my problem...
the class path should be like
`javac Sample.java
java -classpath "D:\jdk1.6.0_45\sqlite-jdbc-3.7.2.jar";. Sample`
the problem is solved:)
How can I populate a list with data from a SQLite database in my Blackberry application? I can view the list, but I can see only one item which is the last item from my database table in the list. Below is the code:
import net.rim.device.api.ui.component.*;
import net.rim.device.api.ui.container.*;
import net.rim.device.api.database.Database;
import net.rim.device.api.database.DatabaseFactory;
import net.rim.device.api.database.Row;
import net.rim.device.api.database.Statement;
import net.rim.device.api.io.URI;
class ListFieldScreen extends MainScreen
{
Database d;
public ListFieldScreen()
{
final ObjectListField list = new ObjectListField();
try
{
URI myURI=URI.create("file:///SDCard/Databases/MyTestDatabase.db");
d=DatabaseFactory.open(myURI);
Statement st=d.createStatement("SELECT eng FROM English");
st.prepare();
net.rim.device.api.database.Cursor c=st.getCursor();
Row r;
while(c.next())
{
r=c.getRow();
String w=r.getString(0);
String[] t={w};
list.set(t);
add(list);
}
st.close();
d.close();
}
catch ( Exception e ) {
e.printStackTrace();
}
}
}
Try like this:
First declare as
public Vector tableVector;
public ObjectListField list;
and call this below code in separate method;
tableVector=new Vector();//Declare this before the method;
try
{
//Uri creation
Statement st=LoadingScreen.database.createStatement("YOUR Statement");
st.prepare();
Cursor c = st.getCursor();
Row r;
while(c.next())
{
r = c.getRow();
tableVector.addElement(r.getString(0));
}
st.execute();
st.close();
}
catch(Exception e)
{
//Exception;
}
After complete this method; show the data as...
String ar[]=new String[tableVector.size];
for(int i=0;i<tableVector.size;i++)
{
ar[i]=tableVector.elementAt(i).toString();
}
list.set(ar);
add(list);
I suppose you need to specify number of items you want to show in the list - I mean number of ites from db -