LuaSQL, which seems to be the canonical library for most SQL database systems in Lua, doesn't seem to have any facilities for quoting/escaping values in queries. I'm writing an application that uses SQLite as a backend, and I'd love to use an interface like the one specified by Python's DB-API:
c.execute('select * from stocks where symbol=?', t)
but I'd even settle for something even dumber, like:
conn:execute("select * from stocks where symbol=" + luasql.sqlite.quote(t))
Are there any other Lua libraries that support quoting for SQLite? (LuaSQLite3 doesn't seem to.) Or am I missing something about LuaSQL? I'm worried about rolling my own solution (with regexes or something) and getting it wrong. Should I just write a wrapper for sqlite3_snprintf?
I haven't looked at LuaSQL in a while but last time I checked it didn't support it. I use Lua-Sqlite3.
require("sqlite3")
db = sqlite3.open_memory()
db:exec[[ CREATE TABLE tbl( first_name TEXT, last_name TEXT ); ]]
stmt = db:prepare[[ INSERT INTO tbl(first_name, last_name) VALUES(:first_name, :last_name) ]]
stmt:bind({first_name="hawkeye", last_name="pierce"}):exec()
stmt:bind({first_name="henry", last_name="blake"}):exec()
for r in db:rows("SELECT * FROM tbl") do
print(r.first_name,r.last_name)
end
LuaSQLite3 as well an any other low level binding to SQLite offers prepared statements with variable parameters; these use methods to bind values to the statement parameters. Since SQLite does not interpret the binding values, there is simply no possibility of an SQL injection. This is by far the safest (and best performing) approach.
uroc shows an example of using the bind methods with prepared statements.
By the way in Lua SQL there is an undocumented escape function for the sqlite3 driver in conn:escape where conn is a connection variable.
For example with the code
print ("con:escape works. test'test = "..con:escape("test'test"))
the result is:
con:escape works. test'test = test''test
I actually tried that to see what it'd do. Apparently there is also such a function for their postgres driver too. I found this by looking at the tests they had.
Hope this helps.
Related
I have an exam using SQLPlus and sometimes I don't remember the exact syntax of SQL statements, so I was wondering if there is any way to get some nice inline help from inside SQLPlus.
For instance, say I forgot how to use INSERT INTO, and I want some reminder like this:
INSERT INTO table-name (column-names)
VALUES (values)
Is this possible?
I tried HELP command but none of that seems to suits my needs.
I Googled it with no success.
No. SQL is a standardized language (at least ANSI SQL) and SQLPlus "just" uses that syntax, so it's not covered by internal help. Internal help lists only SQLPlus specific commands (ex. SET, CONNECT, SPOOL).
It is possible to workaround that in some way, but very limited. You can call dbms_metadata.get_ddl function for some existing object. Some of those DDLs could have statements you are intrested in. For example - you'd like to see select statement - then you could call dbms_metadata.get_ddl for some existing view:
select dbms_metadata.get_ddl('VIEW', 'USER_TABLES', 'SYS')
from dual;
Be aware - it works only for Oracle 11G and lower, in the newest one SYS objects are not accessible in that way (I'm not sure about Oracle 12.1).
The more interesting are tiggers, procedures, functions, and packages. You cannot use dbms_metadata to get DDLs of packages owned by SYS, but maybe you can connect to some sample schemas like HR (Human Resources), AD (Academic), SH (Sales History).
In HR schema there is stored procedure ADD_JOB_HISTORY, which has inside insert statement, so it looks like that:
select dbms_metadata.get_ddl('PROCEDURE', 'ADD_JOB_HISTORY')
from dual;
CREATE OR REPLACE EDITIONABLE PROCEDURE "HR"."ADD_JOB_HISTORY"
( p_emp_id job_history.employee_id%type
, p_start_date job_history.start_date%type
, p_end_date job_history.end_date%type
, p_job_id job_history.job_id%type
, p_department_id job_history.department_id%type
)
IS
BEGIN
INSERT INTO job_history (employee_id, start_date, end_date,
job_id, department_id)
VALUES(p_emp_id, p_start_date, p_end_date, p_job_id, p_department_id);
END add_job_history;
There are better ways and better tools to achieve your goal - see below.
Are you allowed to use SQL Developer instead of SQLPlus? SQL Developer has nice feature to drag-and-drop table icon into worksheet, then you will be nicely prompted to choose what kind of example statement you are looking for (SELECT, INSERT, UPDATE etc.) - after choosing one you will get sample statement.
But the best way is just open in browser Database SQL Language Reference:
https://docs.oracle.com/database/121/SQLRF/toc.htm
I have a problem which I have been trying to resolve since yesterday. I am trying to pass an SQL Query via $wpdb on wordpress but I keep getting an empty array when I try to echo the result.
I have tried print_r and var_dump and both are giving me empty values. I would appreciate if someone can help as I cannot seem to get this thing sorted.
I have also tried calling the table via the db prefix with still no success.
Below is the code I have been using
<?php
global $wpdb;
$results = $wpdb->get_results("SELECT CURRENT FROM upper_winds WHERE LVL=&level AND REGION=®ion AND VALID=&valid");
echo $results;
?>
P.S I have also tried get_var with the same problems.
Thanks
I noticed you weren't accounting for the wordpress database prefix, which could be why your results aren't showing up. You can prepend the prefix to your table name by using $wpdb->prefix.
I would suggest trying the following code:
global $wpdb;
$results = $wpdb->get_results("SELECT * FROM ".$wpdb->prefix."upper_winds WHERE LVL = 'level' AND REGION = 'region' AND VALID = 'valid'");
echo $results;
I also just wanted to point out that it's important to use $wpdb->prepare to protect against SQL Injection attacks. Any time you are writing your own SQL, you need to use $wpdb->prepare. However when you use methods like $wpdb->insert or $wpdb->update that don't require you to write any SQL, then you do not need to use $wpdb->prepare because those functions take care of SQL Escaping for you. I can't provide sample code without knowing which of your values are strings and which values are integers.
See: http://codex.wordpress.org/Class_Reference/wpdb#Protect_Queries_Against_SQL_Injection_Attacks
you need to prefix your table more than likely this is wp_ etc..
<?php
global $wpdb;
$results = $wpdb->get_results("SELECT * FROM `wp_upper_winds`
WHERE `LVL`='$level'
AND `REGION`='$region'
AND `VALID`='$valid'
");
var_dump ($results);
?>
you are looking for strings in your columns but using the &?
Thanks for your great advice and input. Eventually I got it to work.
The problem was not only in the code as I had been changing my code many times to try to find the solution. Eventually the main problem was nailed down to the table. Within one of the columns I had data which was something like this 'EU-VFR'. Apparently $wpdb did not pick up values with a '-'. Luckily with your help and some debugging I realised.
Here is what I got now http://howtoflyahelicopter.com/upper-winds-and-temp/
Thanks again :)
I am using Delphi 2010 and UIB to access a Firebird database.
I am trying to run the Query
SELECT
RECID
FROM TABLE
WHERE ((:DX = '') OR (DX=:DX))
AND ((:POSTCODE='') OR (POSTCODE=:POSTCODE))
Note, that I am using each named parameter twice in the statement.
When I prepare it in a TUIBQuery I get ParamCount=2 and two parameters named DX. When I trace the code I see TSQLParams.Parse passing over the my SQL and calling AddFieldA four times. I can see that duplicates are recognized and added to the end of FXSQLDA, but FParamCount is not incremented.
As a temporary dumb fix I have added such an increment and I now get (DX, DX, POSTCODE, POSTCODE) as parameter-list. That sort of works.
Questions:
Is the sort of parameter-reuse I am attempting supported by Firebird?
By UIB?
Is my fix viable?
Are there better fixes?
Firebird itself does not support named parameters in dynamic SQL (it does in procedural SQL). Firebird only supports positional parameters.
So it is your driver that translates named parameters to positional.
Is librdf_model_add writing the statements into the hash-storage?
I am having problem to run a sparql query to retrieve them. The db files are probably populated as their file size keep increasing, but when I attempt to perform sparql query to them I don't seem to get any result. Do I need to load the statements from the storage into the model manually before issuing a query?
the statement that issue the query
$query = librdf_new_query(
$world,
'sparql',
NULL,
<<<SPARQL
PREFIX sensei: <http://coolsilon.com/flickr_schema/>
SELECT ?a ?c
WHERE {?a ?b ?c}
SPARQL
,
NULL
);
$result = librdf_query_execute($query, $model);
var_dump(librdf_query_results_get_count($result)); // returns 0
I am using PHP (5.3.5) language binding, and my redland version is 1.0.12 running under Ubuntu Natty.
p/s: I checked again with postgresql storage, and the above code works :/
This is better asked on semantic overflow or the redland-dev list.
The most likely thing is the model has no data.
Use some of the librdf functions to print out the model or use a serializer.
Try the test.php for pointers in https://github.com/dajobe/redland-bindings/tree/master/php
I want to output the query generated by a symfony propel select for testing purposes. Is there any way to do this? I know I can use the sf_debug bar, but sometimes I need to see the statement in a situation where the sf_debug bar hasn't loaded yet, or isn't going to load at all.
Timmow is right that there is a Criteria::toString() method, but it's not the magic _toString() method that's automatically called when the object is referenced as a string.
If you want to see the SQL you have to explicitly call Criteria::toString().
$c = new Criteria();
// HERE: add criteria
// what's it do?
echo $c->toString(); // oh, that's what it does
Propel Criteria objects have a toString method, so you should simply be able to echo / var_dump / log to a file the criteria object you are interested in
It also might be helpful to take a look at Day 6 of the Jobeet Tutorial, Debugging Propel generated SQL. If you're in the debug environment, the raw queries are output to the log files. Not 100% sure as I use Doctrine.
You'll get the generated SQL statement that way after you've build the criteria :
$params= array();
$resulting_sql_statement = BasePeer::createSelectSql($criteria,$params);