how to try execute repeatly if command.ExecuteNonQuery() fails - tsql

how to try execute repeatly if command.ExecuteNonQuery() fails?

You can try
bool executed = false;
while (!executed)
{
try
{
command.ExecuteNonQuery();
executed = true;
}
catch
{
}
}
You can add some more conditions like a timer or a counter but this does not seem to be a good idea. You should probably come up with a better recovery scenario.

The simplest way I can think is:
while(true) {
try {
command.ExecuteNonQuery();
break;
} catch(SqlException ex) { }
}
You should anyway put some extra control code in the catch block to prevent an infinite loop and/or to log the error.

Related

Dart cannot break out of loop while inside awaited then callback

I'm trying to generate random int and check if the integer is exists in Firebase database, and do this infinitly until the integer is not exist inside database.
Below my code:
while (true) {
_changeRandomInt()
firebaseFirestore.collection("myCollection").doc(_randomInt).get().then((DocumentSnapshot documentSnapshot) {
if (getFromFirebase(documentSnapshot) == null) {
break;
}
});
}
But I cannot even run this code. Error: A break statement can't be used outside of a loop or switch statement. Try removing the break statement. I have my break inside while loop, then why I'm getting this error? How to fix this?
A break statement can't be used outside of a loop or switch statement. Try removing the break statement.
This is self explanatory. You can't use break outside of a loop. Which in your case is inside a future.
Do something like this:
_changeRandomInt();
firebaseFirestore.collection("myCollection").doc(_randomInt).get()
.then((DocumentSnapshot documentSnapshot) {
while (getFromFirebase(documentSnapshot) != null){
//the body of this loop will only execute as long as the value isn't null
//will break out of the loop as soon as the value is null
}
}
The break you have used is inside then(), which means no loop is available immediately above `break. You can refactor your code in this manner to get it working.
while (true) {
_changeRandomInt()
final documentSnapshot = await firebaseFirestore.collection("myCollection").doc(_randomInt).get();
if (getFromFirebase(documentSnapshot) == null) {
break;
}
}
If getFromFirebase is also a future, then await that as well inside if block.
You want to do something like this:
void functionName() async {
try{
var ans;
while(getFromFirebae(ans)== null){
ans = await firebaseFirestore.collection("myCollection").doc(_randomInt).get();
}
} catch(e){
//error
}
}
However, this is not the correct way. A good practice is to create a loading widget, that would show an animation while the future is loading. An even better way - to load everything in the background without stalling the overall app.
Some people have been saying that you're using "break inside a Future", but that's not quite right. Your problem is that you're using break inside of a separate function body. This is equivalent to writing:
void f() {
break;
}
which doesn't make sense since break is not used directly within a local loop or switch statement. It doesn't matter that you're creating your function within a loop; break and continue statements perform local control flow (within a function), not across functions.
In general, instead of using Future.then, you should prefer using async/await which will have the compiler generate the callback function with appropriate code transformations for you:
while (true) {
_changeRandomInt()
var documentSnapshot =
await firebaseFirestore.collection("myCollection").doc(_randomInt).get();
if (getFromFirebase(documentSnapshot) == null) {
break;
}
}
Note that performing an asynchronous operation continuously in a loop isn't very efficient, so you probably should consider alternative approaches if possible, however.

How to break out of a loop in project reactor?

I want to write some codes using reactor like this:
String callRemote(String server){
//remote call
...
}
List<String> servers = ...
String result = null;
for(String server: servers){
try{
result = callRemote(server); // should be called in sequence
if(result.equals("success")){
break;
}
}catch(TimeoutException e){ //timeout control
//
}
}
At the beginning, I think Flux.takeWhile will be a good choice, but it is hard to control the timeout for every callRemote.
And then I tried Mono.zipWhen and Mono.then , but I cant break the execution chain.
You may use filterWhen():
// return async first success
return Flux.just(servers).flatMap(this::connect)
.filterWhen(result -> Mono.just(result.equalsIgnoreCase("success"));
Check Javadoc of filterWhen()

should I set T-SQL command timeout back to default?

I hope this question is not too stupid. I have a long process t-sql command in my ADO.Net. I would like to increase the command timeout (please see below).
cmd.CommandTimeout = 600; // default is 30 sec. increase to 10 mins
try
{
cmd.ExecuteNonQuery();
cmd.CommandTimeout = 30; // set it back
}
catch (Exception ex)
{
string debug = ex.Message;
throw ex;
}
Should I set the timeout back to default after the long process is done? I am looking for the best practice. Thank you :-)
If you re-use the command object, you can add a finally to the try-catch, so it will be reset regardless of the result of the query. (success or exception).
But when you dispose the SqlCommand after you've used it. There's no need to reset the CommandTimeout
The best practice is to not reuse the command because you should not be reusing the connection. Holding a connection is not good for scale.
static private dbConnectionString = "CONNECTION DETAILS";
using (SQLConnection connection = new SQLConnection(dbConnectionString))
{
try
{
connection.Open();
using (SQLCommand command = connection.CreateCommand())
{
command.CommandTimeout = 600;
......
using(SQLDataReader rdr = command.ExecuteReader())
{
}
}
}
catch(SQLException ex)
{
}
finally
{
connection.Close();
}
}

VACUUM cannot run inside a transaction block

My application has this code:
Connection connection = DriverManager.getConnection(url, userName, password);
connection.setAutoCommit(false);
try {
Statement statement = connection.createStatement();
try {
statement.executeUpdate("TRUNCATE mytable");
} finally {
statement.close();
}
connection.commit();
connection.setAutoCommit(true);
statement = connection.createStatement();
try {
statement.executeUpdate("VACUUM mytable");
} finally {
statement.close();
}
connection.setAutoCommit(false);
connection.commit();
} finally {
connection.close();
}
It fails on statement.executeUpdate("VACUUM mytable"); because VACUUM cannot run inside a transaction block.
I must be missing some notions as I thought that setting the autocommit to true would remove the transaction context (needed for TRUNCATE). Apparently it doesn't. So how do I get out of the transactional context and perform my VACUUM successfully? How should I write my code to not have this transactional context?

method retuns error code or what is the best way to do that

i have a class like this:
class myclass {
public function save($params){
// some operations
// posible error
return false;
// some more code
// posible error
return false;
// more code
// if everything is ok
return true;
}
}
but what is the best way to display errors, one idea is make the class return numbers like for example:
public function save($params) {
// some operations
// some error with the db
return 1;
// more code
// some error with a table
retunr 2;
// more code
// if everything is ok
return 0;
}
and when al call this function, make a switch in order to display the errors:
$obj = new myclass();
$err = $obj->save($params);
switch($err) {
case 1: echo 'error with the db'; break;
case 2: echo 'error with some table'; break;
default: echo 'object saved!';
}
is this the best way to write this? or there is another way?
Many programming languages give you the option to throw and catch exceptions. Where available, this is generally a better error handling model.
public function save($params) throws SomeException {
// some operations
if (posible error)
throw new SomeException("reason");
}
// client code
try {
save(params);
} catch (SomeException e) {
// log, recover, abort, ...
}
Another advantage of Exceptions is that they will (at least in some languages) give you access to stack trace as well as message.