I keep getting a syntax error on this code [duplicate] - sqlite

I'm trying to insert some information to MySQL with Pascal, but when I run the program I get the error
unknown column 'mohsen' in field list
This is my code
procedure TForm1.Button1Click(Sender: TObject);
var
aSQLText: string;
aSQLCommand: string;
namee:string;
family:string;
begin
namee:='mohsen';
family:='dolatshah';
aSQLText:= 'INSERT INTO b_tbl(Name,Family) VALUES (%s,%s)';
aSQLCommand := Format(aSQLText, [namee, family]);
SQLConnector1.ExecuteDirect(aSQLCommand);
SQLTransaction1.Commit;
end;
How can I solve this problem?

It's because your
VALUES (%s,%s)
isn't surrounding the namee and family variable contents by quotes. Therefore, your back-end Sql engine thinks your mohsen is a column name, not a value.
Instead, use, e.g.
VALUES (''%s'',''%s'')
as in
Namee := 'mohsen';
Family := 'dolatshah';
aSQLText:= 'INSERT INTO b_tbl(Name,Family) VALUES (''%s'',''%s'')';
aSQLCommand := Format(aSQLText,[namee,family]);
In the original version of my answer, I explained how to fix your problem by "doubling up" single quotes in the Sql you were trying to build, because it seemed to me that you were having difficulty seeing (literally) what was wrong with what you were doing.
An alternative (and better) way to avoid your problem (and the one I always use in real life) is to use the QuotedStr() function. The same code would then become
aSQLText := 'INSERT INTO b_tbl (Name, Family) VALUES (%s, %s)';
aSQLCommand := Format(aSQLText, [QuotedStr(namee), QuotedStr(family)]);
According to the Online Help:
Use QuotedStr to convert the string S to a quoted string. A single quote character (') >is inserted at the beginning and end of S, and each single quote character in the string is >repeated.
What it means by "repeated" is what I've referred to as "doubling up". Why that's important, and the main reason I use QuotedStr is to avoid the Sql db-engine throwing an error when the value you want to send contains a single quote character as in O'Reilly.
Try adding a row containing that name to your table using MySql Workbench and you'll see what I mean.
So, not only does using QuotedStr make constructing SQL statements as strings in Delphi code less error-prone, but it also avoid problems at the back-end, too.

Just in case this will help anybody else I had the same error when I was parsing a python variable with a sql statement and it had an if statement in i.e.
sql="select bob,steve, if(steve>50,'y','n') from table;"
try as I might it coming up with this "unknown column y" - so I tried everything and then I was about to get rid of it and give it up as a bad job until I thought I would swap the " for ' and ' for "..... Hoooraaahh it works!
This is the statement that worked
sql='select bob,steve, if(steve>50,"y","n") from table;'
Hope it helps...

To avoid this sort of problem and SQL injection you should really look into using SQL parameters for this, not the Pascal format statement.

Related

Teradata remove enclosing single quotes from variable

I need to replace single quotes in a string of numbers and use in a WHERE IN clause. for example, I have
WHERE Group_ID IN (''4532','3422','1289'')
The criteria within parenthesis is being passed as a parameter, so I have no control over that. I tried using :
WHERE Group_ID IN (REGEXP_REPLACE(''4532','3422','1289'', '[']', ' ',1,0,i))
also tried using OReplace
WHERE Group_ID IN (OReplace(''4532','3422','1289'', '[']', ' '))
but get the same error:
[Teradata Database] [3707] Syntax error, expected something like ','
between a string or a Unicode character literal and the integer '4532'.
Please suggest how to remove the single enclosing quotes or even removing all single quotes should work as well.
The string ''4532','3422','1289'' you are using is incorrect because it contains non-escaped single quotes. This is a syntax error in SQL. In this particular form, no matter what function you use to fix it or which RDBMS you use, it will result in error with standard SQL.
Functions in the SQL cannot fix syntax errors. REGEXP_REPLACE and OReplace never get executed because the query never enters the execution state. It never goes past the SQL syntax parser.
To see the error from perspective of the SQL parser, you may break the string in to multiple parts
'' -- SQL Parser sees this as a starting and ending quote and hence an empty string
4532 -- Now comes what appears to SQL parser as an integer value
',' -- Now this is a pair of quotes containing a single comma
3422 -- Again an integer
',' -- Again a comma
1289 -- Again integer
'' -- Again emtpy string
This amalgam of strings and numbers will not mean anything to the SQL parser and will result in an error.
Fix
The fix is to properly escape the data. Single quotes must be escaped using another preceding single quote. So correct string in this scenario becomes '''4532'',''3422'',''1289'''
Another thing is that the OReplace usage (once syntax is fixed) is like OReplace(yourStringValueHere, '''', ' ')) Observe the usage of escaped single quote here. Two outer quotes are for the string start and end. First inner quote is the escape character and second inner quote is the actual data passed to the function.

Bracket-escaped table names with dplyr

I'm programmatically fetching a bunch of datasets, many of them having silly names that begin with numbers and have special characters like minus signs in them. Because none of the datasets are particularly large, and I wanted the benefit R making its best guess about data types, I'm (ab)using dplyr to dump these tables into SQLite.
I am using square brackets to escape the horrible table names, but this doesn't seem to work. For example:
data(iris)
foo.db <- src_sqlite("foo.sqlite3", create = TRUE)
copy_to(foo.db, df=iris, name="[14m3-n4m3]")
This results in the error message:
Error in sqliteSendQuery(conn, statement, bind.data) : error in statement: no such table: 14m3-n4m3
This works if I choose a sensible name. However, due to a variety of reasons, I'd really like to keep the cumbersome names. I am also able to create such a badly-named table directly from sqlite:
sqlite> create table [14m3-n4m3](foo,bar,baz);
sqlite> .tables
14m3-n4m3
Without cracking into things too deeply, this looks like dplyr is handling the square brackets in some way that I cannot figure out. My suspicion is that this is a bug, but I wanted to check here first to make sure I wasn't missing something.
EDIT: I forgot to mention the case where I just pass the janky name directly to dplyr. This errors out as follows:
library(dplyr)
data(iris)
foo.db <- src_sqlite("foo.sqlite3", create = TRUE)
copy_to(foo.db, df=iris, name="14M3-N4M3")
Error in sqliteSendQuery(conn, statement, bind.data) :
error in statement: unrecognized token: "14M3"
This is a bug in dplyr. It's still there in the current github master. As #hadley indicates, he has tried to escape things like table names in dplyr to prevent this issue. The current problem you're having arises from lack of escaping in two functions. Table creation works fine when providing the table name unescaped (and is done with dplyr::db_create_table). However, the insertion of data to the table is done using DBI::dbWriteTable which doesn't support odd table names. If the table name is provided to this function escaped, it fails to find it in the list of tables (the first error you report). If it is provided escaped, then the SQL to do the insertion is not synatactically valid.
The second issue comes when the table is updated. The code to get the field names, this time actually in dplyr, again fails to escape the table name because it uses paste0 rather than build_sql.
I've fixed both errors at a fork of dplyr. I've also put in a pull request to #hadley and made a note on the issue https://github.com/hadley/dplyr/issues/926. In the meantime, if you wanted to you could use devtools::install_github("NikNakk/dplyr", ref = "sqlite-escape") and then revert to the master version once it's been fixed.
Incidentally, the correct SQL-99 way to escape table names (and other identifiers) in SQL is with double quotes (see SQL standard to escape column names?). MS Access uses square brackets, while MySQL defaults to backticks. dplyr uses double quotes, per the standard.
Finally, the proposal from #RichardScriven wouldn't work universally. For example, select is a perfectly valid name in R, but is not a syntactically valid table name in SQL. The same would be true for other reserved words.

Getting the rowtype of a table named after an Oracle PL/SQL keyword

I have a table named CASE.
And let's say I have the ff code:
declare
a CASE%rowtype;
begin
null;
end;
The above code will throw the error: PLS-00103: Encountered the symbol "CASE" when expecting one of the following: ...
Is there anyway for me to create a variable of CASE%rowtype without manually creating the datatype itself? Thanks!
as Case is a reserved keyword,
you can escape it with double quotes
a "CASE"%rowtype;
useless to say that you should avoid reserved keywords in object naming... (or not that useless ?)

How to do a column name inside of a dynamic where clause? TO_NUMBER(column name)

I am currently trying to create a dynamic Select statement when the user has to input a various amount of criteria to search by.
Currently, I have every part of the statement working except for the most important part.
I am attempting to do something like this:
selStmt := 'SELECT column_one, column_2, column_3
FROM nerf
whereClause := ' WHERE TO_NUMBER('''|| column_one ||''') <= '''|| userInput ||'''';
However, in doing this the WHERE cluse of my SELECT statement is not accurate as shown by my output line:
WHERE TO_NUMBER('') <= '5';
I have tried various solutions with quote marks and I end up with either a ORA-00905 missing identifier error, or I get a ORA-00911: invalid character error.
At this point I'm not quite sure how to approach this issue.
Any useful help gets thanks in advance.
For some reason, Oracle uses the single quote to delimit strings and to escape characters, so using '' is an instruction to Oracle to add a quote inside your string. Example:
'This is a string with a quote here: '' and then it ends normally'
will be represented as
This is a string with a quote here: ' and then it ends normally
In your example, you are ending the WHERE clause you're building up and then concatenating a PL/SQL variable identifier called column_one:
' WHERE TO_NUMBER('''|| column_one ||''')
...and with a NULL value for the identifier column_one this is represented as
WHERE TO_NUMBER('')
Presumably you want to reference column_one from inside the query, and not from a PL/SQL variable of the same name, so you should remove the quotes around it like so:
whereClause := ' WHERE TO_NUMBER(column_one) <= TO_NUMBER('''|| userInput ||''')';
Escaping strings in Oracle is often infuriating - it helps a lot if you have a good IDE with decent syntax highlighting like TOAD or SQL*Developer.
This should work:
selStmt := 'SELECT column_one, column_2, column_3 FROM nerf';
whereClause := ' WHERE TO_NUMBER(column_one) <= TO_NUMBER('''|| userInput ||''')';

swi-prolog odbc error while inserting into postgresql

I have the following problem and I'm begging for help: I'm using swi-prolog and odbc interface to connect to postgresql database. Problem occurs when I try to insert in database. SELECT works fine but INSERT doesn't work. Does anybody know what am I doing wrong.
Here's my simple test code:
:-use_module(library(odbc)).
connect(C):-
odbc_connect(baza, C, [user(Mat),
password(lozinka), alias(baza), open(once)]).
sel(R) :-
odbc_query(baza,
'SELECT * FROM pacijent',
R).
ins:-
odbc_query(baza, 'INSERT INTO pacijent (name, surname, passw, number) VALUES ("James", "Bond", 007, 007)').
This is the error when i try to insert:
?- ins.
ERROR: ODBC: State S1000: [unixODBC]ERROR: column "James" does not exist at character 30;
Error while executing the query
Also i tried to insert through psql console and everything works fine, but as said problem is when inserting from prolog.
Please help, im stuck here.
Thanks
A suggestion: proper escaping, don't know if it'll be enough though. I'd turn
"James", "Bond"
into
\'James\', \'Bond\'
The problem is you've passed the column data for columns name and surname in double quotes instead of single quotes. Most databases use " (double quotes) for identifiers like table and column names and ' (single quotes) for data. How you ensure that in prolog I don't know.
I suspect you'll want to quote the other 2 columns as well.
In ODBC you'd use SQLGetInfo and get SQL_IDENTIFIER_QUOTE_CHAR which will usually return double quotes meaning to quote identifiers use these quotes.

Resources