how do you detect createUpdate() fails? - sql2o

public Connection executeUpdate() {
long start = System.currentTimeMillis();
try {
this.logExecution();
PreparedStatement statement = this.buildPreparedStatement();
this.connection.setResult(statement.executeUpdate());
this.connection.setKeys(this.returnGeneratedKeys ? statement.getGeneratedKeys() : null);
this.connection.setCanGetKeys(this.returnGeneratedKeys);
} catch (SQLException var7) {
this.connection.onException();
throw new Sql2oException("Error in executeUpdate, " + var7.getMessage(), var7);
} finally {
this.closeConnectionIfNecessary();
}
long end = System.currentTimeMillis();
logger.debug("total: {} ms; executed update [{}]", new Object[]{end - start, this.getName() == null ? "No name" : this.getName()});
return this.connection;
}
I'm wondering how to test an update failing. The query I'm using is:
update my_table set some_field=:some_value
where the_key = :the_key_value
And, immediately before executeUpdate() runs, I am deleting the record where the_key == "the_key_value".
Does anyone know the correct way to determine if the update failed?
Also, when I go to the javadoc and click on anything, I get:
CDN object Not Found - Request ID: c6a9ba5f-f8ea-46ae-bf7a-efc084971878-19055563
Is there a way to build javadoc locally?
EDIT: is the way to check this thru the use of Connection.getResult()? Does it return the number of records updated/inserted etc?

I went and RTFM which explained how to do this.

Related

Can't update Boolean value in Apex

I cannot update update this Boolean value in Apex. What is going wrong? The if statement, and the fact that the front end representation is a checkbox, proves that it is indeed a boolean value. I am new to Apex so I feel its a basic misunderstanding of how it works. Can anyone help me out?
Here is the code that I'm executing in an Anonymous Window.
Account acc = new Account(Name='Test Name');
if (acc.Do_Not_Contact__pc == false) {
System.debug('DNC is false');
} else {
System.debug('DNC is true');
}
insert acc;
acc.Do_Not_Contact__pc = true;
update acc;
It fails on the second to last line, displaying the following message:
System.DmlException: Update failed. First exception on row 0 with id 001W000000fFiVbIAK; first error: INVALID_FIELD_FOR_INSERT_UPDATE, Account: bad field names on insert/update call: Do_Not_Contact__pc: [Do_Not_Contact__pc]
What's particularly frustrating is that when I change the second to last line to
acc.Do_Not_Contact__pc = 'true';
I get an error stating that I cannot assign a String to a Boolean value
Remove the single quotes and I assume you typed the field name wrong. Try acc.Do_Not_Contact__c = true;

Pagination in Google cloud endpoints + Datastore + Objectify

I want to return a List of "Posts" from an endpoint with optional pagination.
I need 100 results per query.
The Code i have written is as follows, it doesn't seem to work.
I am referring to an example at Objectify Wiki
Another option i know of is using query.offset(100);
But i read somewhere that this just loads the entire table and then ignores the first 100 entries which is not optimal.
I guess this must be a common use case and an optimal solution will be available.
public CollectionResponse<Post> getPosts(#Nullable #Named("cursor") String cursor,User auth) throws OAuthRequestException {
if (auth!=null){
Query<Post> query = ofy().load().type(Post.class).filter("isReviewed", true).order("-timeStamp").limit(100);
if (cursor!=null){
query.startAt(Cursor.fromWebSafeString(cursor));
log.info("Cursor received :" + Cursor.fromWebSafeString(cursor));
} else {
log.info("Cursor received : null");
}
QueryResultIterator<Post> iterator = query.iterator();
for (int i = 1 ; i <=100 ; i++){
if (iterator.hasNext()) iterator.next();
else break;
}
log.info("Cursor generated :" + iterator.getCursor());
return CollectionResponse.<Post>builder().setItems(query.list()).setNextPageToken(iterator.getCursor().toWebSafeString()).build();
} else throw new OAuthRequestException("Login please.");
}
This is a code using Offsets which seems to work fine.
#ApiMethod(
name = "getPosts",
httpMethod = ApiMethod.HttpMethod.GET
)
public CollectionResponse<Post> getPosts(#Nullable #Named("offset") Integer offset,User auth) throws OAuthRequestException {
if (auth!=null){
if (offset==null) offset = 0;
Query<Post> query = ofy().load().type(Post.class).filter("isReviewed", true).order("-timeStamp").offset(offset).limit(LIMIT);
log.info("Offset received :" + offset);
log.info("Offset generated :" + (LIMIT+offset));
return CollectionResponse.<Post>builder().setItems(query.list()).setNextPageToken(String.valueOf(LIMIT + offset)).build();
} else throw new OAuthRequestException("Login please.");
}
Be sure to assign the query:
query = query.startAt(cursor);
Objectify's API uses a functional style. startAt() does not mutate the object.
Try the following:
Remove your for loop -- not sure why it is there. But just iterate through your list and build out the list of items that you want to send back. You should stick to the iterator and not force it for 100 items in a loop.
Next, once you have iterated through it, use the iterator.getStartCursor() as the value of the cursor.

List becomes empty After query.closeall methodin jdo

public static List<FieldOption>
getFieldOptionListOfField(PersistenceManager pm, long fieldId) throws NoSuchFieldOptionException {
Query query = pm.newQuery(FieldOption.class);
try {
query.setFilter("this.fieldId == fieldId");
query.declareParameters("long fieldId");
query.setOrdering("orderId ascending");
List<FieldOption> fieldOptions = (List<FieldOption>) query.execute(fieldId);
logger.debug("fieldOptions = " + fieldOptions);
return fieldOptions();
} finally {
query.closeAll();
}
}
After execution of excute method 'fieldOptions' is having certain values. But after closeAll() the list becomes empty. Can you please suggest why it happens?
The "List" returned after you end a transaction and close a PM is not a real List, but instead a lazy load list, that cannot lazy load once it has no connection to the datastore. Easiest option is put (copy) the query results into your own List before closing the txn/PM.

C# login message warning

Well im here because i have a problem. i have code that was created a while ago. my code is working properly when i a user type the correct username and password. so my problem is when a user insert wrong username and password error message wont show. Here is my code:
MyDs.Clear();
MyDa.SelectCommand = Conn.CreateCommand();
MyDa.SelectCommand.CommandText =
"select * from PersonalName where Firstname=#first and Lastname=#last";
MyDa.SelectCommand.CommandType = CommandType.Text;
MyDa.SelectCommand.Parameters.Add("#first", DbType.String, 25, "Firstname").Value = textbox_Username.Text;
MyDa.SelectCommand.Parameters.Add("#last", DbType.String, 25, "Lastname").Value = textbox_Password.Text;
MyDa.Fill(MyDs);
foreach (DataRow item in MyDs.Tables[0].Rows)
{
if (textbox_Username.Text != item[1].ToString() || textbox_Password.Text != item[3].ToString())
{
MessageBox.Show("not connected");
}
else
{
MessageBox.Show("Connected");
}
}
Anyone can tell me what is the problem with this code?
Your dataset will be empty if they put in the wrong username. This will be closer to what you want:
if (MyDs.Tables[0].Rows.Count > 0)
{
// you don't need to check username, the SQL query took care of that
if (textbox_Password.Text == item[3].ToString())
MessageBox.Show("Connected.");
else
MessageBox.Show("Failed."); // wrong password
}
else
MessageBox.Show("Failed."); // no such user
if the query returns no records becasue firast and last name aren't present, foreach doesn't execute nothing happens...
You need to test for myDa being empty as well, your code only works for checking valid users.

Android:Is there a better way to insert and/or update a database entry?

I have a database containing a userId and a note. The user doesn't know if there already is a note in the DB so they write one and click the 'Submit' button. I want to insert this note if there is no note for the userId or update that userId's already existing note:
notesDb.open();
boolean updateResult = notesDb.updateMessage(
userId,
details_notes_input.getText().toString());
if(updateResult == true) {
Log.d("databaseTester", "Updated entry into table");
} else {
Log.d("databaseTester", "FAILED to update entry into table");
long insertResult = notesDb.insertMessage(
userId,
details_notes_input.getText().toString());
if(insertResult == -1){
Log.d("databaseTester", "Failed to insert entry into table");
} else {
Log.d("databaseTester", "Inserted entry into table");
}
}
notesDb.close();
So, I'm pretty much attempting to 'update' an entry and if I fail then I attempt to 'insert' it. I don't know SQL very well, but I would think there would be a better way. Thanks.
It sounds like you could use sqlite's REPLACE to solve this problem, using SQLiteDatabase.replace().
You can catch a constraint exception launched in case of previous ID existence and then update.
try {
db.insertOrThrow("sometable", null, cv);
} catch (SQLiteConstraintException e) {
db.update("sometable", cv,"sometable_uid =" + id, null);
}
Try this
result = db.insertWithOnConflict("tablename ", null, cv, -1);

Resources