Why does try catch not catch Sql syntax error - asp.net

I'm adding an inputbox to my site where I as the admin can enter sql select statements, I put a try catch around the code that executes the select to try and catch syntax errors but even with this my site goes to the "error in application / " page when there is a syntax error.
I don't understand what I am doing wrong. I am developing on Asp.net v4.
The code that executes the custom SQL command is as follows;
try
{
//edtSQL.Text = "WHRE Field='Value'"
//The Resulting SQL Command will be incorrect because of incorrect syntax
SqlDataSource1.SelectCommand = "SELECT * FROM DataTable " + edtSQL.Text;
SqlDataSource1.Select(new DataSourceSelectArguments());
}
catch(Exception ex)
{
//Bad Syntax should be caught here, but it is not. This never get called
// even when there is a syntax error.
lblQueryStatus.Text = "Error, can't execute SQL statment";
}
Instead if the label showing the error message, the site gives an error and goes to the default site error page.

The catch in the above code does actually catch the exception. On the exception set the Select Command to something default that is sure to work ie.
SELECT * FROM Database
And Execute the select. The reason for this is when the page does a post back it tries to execute the select statement that has been set for it and there is not try catch around this(because its in another context) and this is why the server then defaults to the "error in application / " page.
The code should look like this
try
{
//edtSQL.Text = "WHRE Field='Value'"
//The Resulting SQL Command will be incorrect because of incorrect syntax
SqlDataSource1.SelectCommand = "SELECT * FROM DataTable " + edtSQL.Text;
SqlDataSource1.Select(new DataSourceSelectArguments());
}
catch(Exception ex)
{
SqlDataSource1.SelectCommand = "SELECT * FROM DataTable"; //This will work for sure
SqlDataSource1.Select(new DataSourceSelectArguments());
lblQueryStatus.Text = "Error, can't execute SQL statment";
}

Related

IBM Informix ODBC driver C# - The cursor has been previously released and is unavailable

Trying to switch database using Database (database name); query and then execute a query on that database in two separate queries.
However, I got this error: The cursor has been previously released and is unavailable. What does this mean?
Here is the code:
using (OdbcCommand command = new OdbcCommand(null, odbcConnection))
{
if (switchDBName != null)
{
command.CommandText = "Database " + switchDBName + ";";
command.ExecuteNonQuery();
Console.WriteLine("Switched to database: " + switchDBName + " Successfully.");
}
command.CommandTimeout = 0;
command.CommandText = query;
using (OdbcDataReader datareader = command.ExecuteReader())
{
DataTable resultDT = new DataTable();
resultDT.Load(datareader);
Console.WriteLine("ExecuteODBCQuery -- Finished. There are " + resultDT.Rows.Count + " rows.");
return resultDT;
}
}
If I'm following the logic correctly:
you have two different database connections;
you create a cursor-based statement using one connection;
you switch to the other database connection;
you get an error indicating that the cursor is not available on the current connection
albeit with not wholly appropriate wording in the error message.
A prepared statement or a cursor-based statement is associated with a connection. The same statement will not work for another connection; you have to recreate the cursor or prepared statement for each database connection.
You must know which connection was used for each prepared statement or cursor-based statement. You can switch connections between uses, but when you try to use a statement, the connection must be the same as was in use when it was prepared.

In JavaFX, How to load database value into textfield?

I try to load database value into textfield. this code is not showing any error. But it also not giving result. It showing blank textfield.
try
{
connection = database_controller.dbconnect();
String query = "Select * from newlead2 where SERIAL_NO ='lead_id'";
resultset = database_controller.dbExecuteQuery(query);
/*preparedstatement =connection.prepareStatement(query);
resultset =preparedstatement.executeQuery();*/
while(resultset.next())
{
String FN = resultset.getString("CUSTOMER_NAME");
Customer_Name.setText(FN);
}
}
catch(SQLException ex)
{
System.err.println("Error:" + ex);
}
I’m going off what you posted in the comments. You aren’t connected to the database, so your resultset is empty. Put in some code to test if these variables are empty. But like others have said it is too hard to answer this question without a more concise example.

How to try catch block in Jmeter.Webdriver webdriver Sampler

I want to do the exception handling in Jmeter.Webdriver Webdriver Sampler
Please let me , How to use try/catch block in Jmeter.Webdriver webdriver Sampler ?
You can do this via normal JavaScript try block, here is an example of taking a screenshot when error occurs:
var pkg = JavaImporter(org.openqa.selenium)
var support_ui = JavaImporter(org.openqa.selenium.support.ui.WebDriverWait)
var conditions = org.openqa.selenium.support.ui.ExpectedConditions
var wait = new support_ui.WebDriverWait(WDS.browser, 5)
var exception = null
WDS.sampleResult.sampleStart()
try {
WDS.browser.get('http://example.com')
wait.until(conditions.presenceOfElementLocated(pkg.By.linkText('Not existing link')))
} catch (err) {
WDS.log.error(err.message)
var screenshot = WDS.browser.getScreenshotAs(pkg.OutputType.FILE)
screenshot.renameTo(java.io.File('screenshot.png'))
exception = err
} finally {
throw (exception)
}
WDS.sampleResult.sampleEnd())
Don't forget to "throw" the error after you handle it otherwise it will be "swallowed" and you get a false positive result.
See The WebDriver Sampler: Your Top 10 Questions Answered article for more tips and tricks
Surround the code with try block and add catch block at the end by giving variable name to capture the exception. (in the example, it is exc)
try as follows:
try{
WDS.sampleResult.sampleStart()
WDS.browser.get('http://jmeter-plugins.org')
var pkg = JavaImporter(org.openqa.selenium)
WDS.browser.findElement(pkg.By.id('what')) // there is no such element with id what
WDS.sampleResult.sampleEnd()
}
catch(exc){ //exc variable name
WDS.log.error("element not found" + exc)
}
in the JMeter log, you can see the complete trace of NoSuchElementException, which is raised when trying to find the element by id with the values as what, which is not present in the HTML.
Note: use View Results in Table to see the Sampler response time.
Reference:
https://jmeter-plugins.org/wiki/WebDriverSampler/
Reference Image:
It is same as how do you do in other IDEs like eclipse.
you can see below code
//try block starts here
try{
wait.until(ExpectedConditions.visibilityOfElementLocated(By.xpath("element"))).click();
}
catch(Exception e)
{
WDS.log.info("Exception is : " +e);//you can print the exception in jmeter log.
}
double quotes should be replaced with the single quote if you are using javascript Since the BeanShell is easy and it is similar to java use BeanShell as much as possible

Flyway reports success even though database gave warnings

We are using Flyway 4 (great tool!) on Oracle.
When invalid DDL is committed, the continuous database build breaks.. and all the team gets an email.. all good so far.
But when, code that breaks one of our stored procedures is committed.. ie procedure gets created, but it fails to compile.. we still get a successful migration reported from Flyway.
During the migration we see something like :
DB: Warning: execution completed with warning (SQL State: 99999 - Error Code: 17110)
..but still the Flyway ant task reports success.
As we have a lot of stored procedures, 9 times out of 10 it is these that are broken by developers, and not the DDL. We really would like Flyway to fail on a warning also. Can anyone advise how best to approach this?
Solved! Found an acceptable solution for us and implemented it as follows, utilising Flyways callback mechanism which is documented on the Flyway website.
There are many callbacks available and are invoked at various points, but the one that appears to suit our needs is afterMigrate. In the callback, we can execute sql (on Oracle) which counts the number of invalid objects in the user schema at hand
So, implementing a java afterMigrate callback as follows does the job:
public void afterMigrate(Connection connection) {
String countInvalidObjs = "select count(*) " +
"from user_objects " +
"where object_type in ('FUNCTION','PROCEDURE','PACKAGE','PACKAGE BODY','TRIGGER') " +
"and status = 'INVALID' ";
int invalidObjCount = -1;
Statement statement;
try {
statement = connection.createStatement();
ResultSet rs = statement.executeQuery(countInvalidObjs);
while (rs.next()) {
invalidObjCount = rs.getInt(1);
}
} catch(Throwable t) {
System.out.println("*error* " + t.getMessage());
} finally {
if(invalidObjCount!=0) {
throw new IllegalArgumentException("fail to complete migration, build finished with databse warnings");
}
}
}

Debug Mode: See what is in SqlCommand

I'd like to see what is about to be sent to the SQL Server from my SqlCommand before SQLCmd.ExecuteNonQuery() runs.
I'm trying to debug because I am receiving the following error: System.FormatException: Failed to convert parameter value from a String to a Int32.
Normally, I would use SQL Server Profiler to view what is being sent to SQL Server, but my statement is not making it that far.
Is there a way to determine what it is trying to convert? I am having problems determining which parameter is causing the error.
There's nothing that can quickly visualize it for you, but you can browse through the object and get at the internal list of parameters and view their names and values individually.
It will likely be faster just to write something that you can pass the command into and it will print out the name, DbType, Value.ToString() and Value.GetType().Name for each parameter.
void PrintCommand(DbCommand command)
{
Console.WriteLine("CommandType: {0}", command.CommandType);
Console.WriteLine("CommandText: {0}", command.CommandText);
foreach(var parameter in command.Parameters)
{
Console.WriteLine(" Parameter {0}, {1}: \"{2}\" ({3})",
parameter.ParameterName,
parameter.DbType,
parameter.Value,
parameter.Value.GetType().Name);
}
}
Try the immediate window:
? SQLCmd.Parameters["#MyParam"].Value

Resources