PDO prepared statement with <> operator in where clause - pdo

I need to know how to handle <> operator used with a parameter in where clause within a prepared statement. Can anyone please show me how to do something similar to 'WHERE field <>:parameter'. Thanks.
Edit : I did not remember to mention that MySQL is my database server.

Up until I discovered this, In ALL examples on the web, I had only seen '=' operator in WHERE clause of prepared statements. But I recently found out that ANY, and I mean ANY, operator logical operator works with prepared statement placeholders, not just '='. As an example, you could have:
<?php
$stmt = $dbHandle->prepare( 'SELECT * FROM table WHERE id <> :ID' );
$stmt->execute( array( ':ID'=> $id ) );
?>
OR even this
<?php
$stmt = $dbHandle->prepare( 'SELECT * FROM table WHERE id <= :ID' );
$stmt->execute( array( ':ID'=> $id ) );
?>
AND, as you may guess,
<?php
$stmt = $dbHandle->prepare( 'SELECT * FROM table WHERE id >= :ID' );
$stmt->execute( array( ':ID'=> $id ) );
?>
It looks logical that PDO should be able to do this but was not sure. So, it was a relief to me to discover this through experimentation. I had always wanted to do that in my code. I hope this saves someone some time.

Related

Passing the result of a subquery as a parameter to PL/SQL package

This seems like such a basic question, but I didn't find anything similar on here...
I am currently generating exec statements by concatenating various strings and columns like this:
SELECT ('exec my_package.my_procedure(input_var1 => ''' || columnA || ''', input_var2 => [... ... ...] || ''');') As sql_stmt FROM myTable;
This worked just fine until I decided to add another input parameter that should get its value from a subquery like this (I left out the irrelevant parts, it's the same query as above just with an added parameter):
input_var_my_id => (select NVL(MAX(my_id)+1,1) from someTable where [various conditions] )
After I added that parameter, I am getting a PLS-00103 error, saying that the symbol SELECT was encountered when ( - + case mod new not null [....]
were expected.
The generated exec statement looks like this:
my_package.my_procedure(input_var1 => 'whatever', input_var_my_id => (select NVL(MAX(my_id)+1,1) from someTable where [various conditions] ));
The subquery itself is valid, if I copy it from the generated statement and execute it, I am getting a single dataset as a result - just as expected.
Is it not possible to pass the result of a subquery as a parameter to a PL/SQL package? Are there any workarounds? Thanks for your help
No, it isn't possible to have a query inside the actual parameter list. You can call some functions directly but only those implemented in PL/SQL. You can't switch to an SQL context. You can see that with a simpler example:
exec dbms_output.put_line(select user from dual);
ORA-06550: line 1, column 28:
PLS-00103: Encountered the symbol "SELECT" when expecting one of the following:
...
You will have to put the query result into a local variable, which is going to be ugly in your generated code; it needs to end up as:
declare
l_input_var_my_id someTable.my_id%type;
begin
select NVL(MAX(my_id)+1,1) into l_input_var_my_id from someTable where [various conditions];
my_package.my_procedure(input_var_my_id => l_input_var_my_id, ...);
end;
You can put all of that in an exec:
exec declare l_input_var_my_id someTable.my_id%type; begin select NVL(MAX(my_id)+1,1) into l_input_var_my_id from someTable where [various conditions]; my_package.my_procedure(input_var_my_id => l_input_var_my_id, ...); end;
... and then generate that from your original query.
But as exec is just a shorthand for an anonymous block and has to be on one line by default, it might be clearer to generate the block - so have that without the exec and with a / on a line on its own. Depends how you plan to call the result, and whether it needs to be easy to read.

Correct sql lite syntax

I am successfully adding a table to an sql lite database but I am struggling with the syntax to write values to the table, please take a look at the code below and advice me on the correct syntax.
Sorry Code!
var db = window.openDatabase("Database", "1.0", "GBA", 200000);
db.transaction(populateDB, errorCB, successCB);
}
// Populate the database
//
function populateDB(tx) {
tx.executeSql('DROP TABLE IF EXISTS vehiclecheck');
tx.executeSql('CREATE TABLE IF NOT EXISTS vehiclecheck (id INTEGER PRIMARY KEY AUTOINCREMENT, checkfield VARCHAR(12), class INTEGER)');
tx.executeSql('INSERT INTO vehiclecheck (checkfield, class) VALUES (' + 'Test' + ',' + 1 + ')');
Try this insertion
tx.executeSql("insert into vehiclecheck(checkfield, class) values(?,?)",["Test",'1']);
You need to escape Test. If you consider your SQL:
INSERT INTO vehiclecheck (checkfield, class) VALUES (Test,1)
You can see the single quotes around Test are missing.
Don't forget that you can use bound params as well. An example is here: http://www.raymondcamden.com/index.cfm/2011/10/20/Example-of-PhoneGaps-Database-Support

DBI: bind_param casts string to ntext -> nvarchar(max) and ntext are incompatible

I have a problem concerning perl DBI's bind_param. The following SQL works:
my $sth = $dbh->prepare("SELECT id FROM table WHERE id = 'string'");
$sth->execute();
While the following doesn't:
my $sth = $dbh->prepare("SELECT id FROM table WHERE id = ?");
$sth->execute('string');
The error the last query causes is:
[ODBC SQL Server Driver][SQL Server]The data types nvarchar(max) and ntext are incompatible in the equal to operator. (SQL-42000)
It seems like bind_param, which gets called by execute, casts 'string' to ntext. How can I work around that?
Consider binding the value type prior the SQL call:
use DBI qw(:sql_types);
my $sth = $dbh->prepare( "SELECT id FROM table WHERE id = ?" );
my $key = 'string';
my $sth->bind_param( 1, $key, SQL_VARCHAR );
$sth->execute();

sql select FROM_UNIXTIME(unix_timestamp) engine independent

I need to convert INT to DATETIME, on SQL Server it would be:
select cast(convert(unix_timestamp,103) AS datetime)
on MySQL the syntax is:
select FROM_UNIXTIME(unix_timestamp)
But i need to make it engine independent(SQL Server, MySQL, T-sql and so on).
is it possible?
Maybe its possible to trick it in PHP?
<?php
$sql='select cast(convert(1350134926,103) AS datetime)';
$result = #mysql_query($sql);
if(!$result){
$sql=' select FROM_UNIXTIME(1350134926)';
$result = #mysql_query($sql);
if(!$result){...}
}
?>

syntax to update all fields in a table in one statement in sql

Can anyone suggest a Syntax to update all fields in a table in one statement.
I want to use it with prepared statement in jdbc.
can anyone suggest a example
Using a prepared statement is not that complicated:
PreparedStatement pstmt = connection.prepareStatement(
"UPDATE my_table SET column_1 = ?, column_2 = ?, column_3 = ?");
// assuming table has columns named as column_1,column_2,column_3 of type int,String,BigDecimal respectively
/* putting the values at runtime */
pstmt.setInt(1, 42); // use value 42 for column_1
pstmt.setString(2, "foo"); // use value 'foo' for column_2
pstmt.setBigDecimal(3, new BigDecimal("123.456")); // use 123.456 for column_3
pstmt.executeUpdate();
connection.commit();
Of course you will need to add error handling to this example.
More examples can be found in the Java Tutorial:
http://download.oracle.com/javase/tutorial/jdbc/basics/prepared.html
UPDATE your_table_name SET field1 = 'value1', field2 = 'value2'
Note : I haven't specified WHERE clause, so these changes will be applied to every single row in a table.