How to put triple qoutes around existing string variable? - string

Let's say I have this variable:
st='MI'
and I want to convert it to:
st=''' 'MI' '''
to use it in a SQL command.
What's the best way to accomplish this?
Thanks in advance!

Tripleor single quoting are just ways of typing strings into source code files.
Once your program is running, your string is already a string, and there is no need to make any cnversion to use it as a parameter to a SQL driver function call.
What you may want i to have a string with an SQL statement that itself contains various (single or double) quote characters. If that is typed in your Python source code file, you can type the triple-quote straight. If you are getting these SQL statements from elsewhere, they are already strings, as I said above.
Now, there are a few instances in which you have a string in a running Python program, or a Python interactive session, that you would like printed, so that you can paste it directly in source code. For these cases you can try the "unicode_escape" codec (and recode it to text so that it does not double your backslashes:
In [56]: print("\n".encode("unicode_escape").decode("utf-8"))
\n

Related

Twincat3 ST variables conversion

I have some complicated array of structures and I want to write it into CSV file. So I need "variable to string" conversion.
Beckhoff as always doesn't care about documentation and their INT_TO_STRING function doesn't work (UNEXPECTED INT_TO_STRING TOKEN when I try to write INT_TO_STRING(20) ).
Moreover their string functions works correctly with only 255 chars.
So I need one of following:
working functions or function blocks or library which allows to convert different types to string
something like sprintf without limitations
some functions to convert between number and ascii char (0x55 is letter 'U') in both directions.
btw. Beckhoff gives us some weird CSV example code, but without data conversion (array has already strings in cells).
Thanks in advance!
I tried to use:
INT_TO_STRING() BYTE_TO_STRING() WHATEVER_TO_STRING()
but it is not working. And there is no clue how many arguments it should have or anything. There is no documentation in Beckhoff information System.

Insert values with single quotes in a Postgres table column [duplicate]

I have a table test(id,name).
I need to insert values like: user's log, 'my user', customer's.
insert into test values (1,'user's log');
insert into test values (2,''my users'');
insert into test values (3,'customer's');
I am getting an error if I run any of the above statements.
If there is any method to do this correctly please share. I don't want any prepared statements.
Is it possible using sql escaping mechanism?
String literals
Escaping single quotes ' by doubling them up → '' is the standard way and works of course:
'user's log' -- incorrect syntax (unbalanced quote)
'user''s log'
Plain single quotes (ASCII / UTF-8 code 39), mind you, not backticks `, which have no special purpose in Postgres (unlike certain other RDBMS) and not double-quotes ", used for identifiers.
In old versions or if you still run with standard_conforming_strings = off or, generally, if you prepend your string with E to declare Posix escape string syntax, you can also escape with the backslash \:
E'user\'s log'
Backslash itself is escaped with another backslash. But that's generally not preferable.
If you have to deal with many single quotes or multiple layers of escaping, you can avoid quoting hell in PostgreSQL with dollar-quoted strings:
'escape '' with '''''
$$escape ' with ''$$
To further avoid confusion among dollar-quotes, add a unique token to each pair:
$token$escape ' with ''$token$
Which can be nested any number of levels:
$token2$Inner string: $token1$escape ' with ''$token1$ is nested$token2$
Pay attention if the $ character should have special meaning in your client software. You may have to escape it in addition. This is not the case with standard PostgreSQL clients like psql or pgAdmin.
That is all very useful for writing PL/pgSQL functions or ad-hoc SQL commands. It cannot alleviate the need to use prepared statements or some other method to safeguard against SQL injection in your application when user input is possible, though. #Craig's answer has more on that. More details:
SQL injection in Postgres functions vs prepared queries
Values inside Postgres
When dealing with values inside the database, there are a couple of useful functions to quote strings properly:
quote_literal() or quote_nullable() - the latter outputs the unquoted string NULL for null input.
There is also quote_ident() to double-quote strings where needed to get valid SQL identifiers.
format() with the format specifier %L is equivalent to quote_nullable().
Like: format('%L', string_var)
concat() or concat_ws() are typically no good for this purpose as those do not escape nested single quotes and backslashes.
According to PostgreSQL documentation (4.1.2.1. String Constants):
To include a single-quote character within a string constant, write
two adjacent single quotes, e.g. 'Dianne''s horse'.
See also the standard_conforming_strings parameter, which controls whether escaping with backslashes works.
This is so many worlds of bad, because your question implies that you probably have gaping SQL injection holes in your application.
You should be using parameterized statements. For Java, use PreparedStatement with placeholders. You say you don't want to use parameterised statements, but you don't explain why, and frankly it has to be a very good reason not to use them because they're the simplest, safest way to fix the problem you are trying to solve.
See Preventing SQL Injection in Java. Don't be Bobby's next victim.
There is no public function in PgJDBC for string quoting and escaping. That's partly because it might make it seem like a good idea.
There are built-in quoting functions quote_literal and quote_ident in PostgreSQL, but they are for PL/PgSQL functions that use EXECUTE. These days quote_literal is mostly obsoleted by EXECUTE ... USING, which is the parameterised version, because it's safer and easier. You cannot use them for the purpose you explain here, because they're server-side functions.
Imagine what happens if you get the value ');DROP SCHEMA public;-- from a malicious user. You'd produce:
insert into test values (1,'');DROP SCHEMA public;--');
which breaks down to two statements and a comment that gets ignored:
insert into test values (1,'');
DROP SCHEMA public;
--');
Whoops, there goes your database.
In postgresql if you want to insert values with ' in it then for this you have to give extra '
insert into test values (1,'user''s log');
insert into test values (2,'''my users''');
insert into test values (3,'customer''s');
you can use the postrgesql chr(int) function:
insert into test values (2,'|| chr(39)||'my users'||chr(39)||');
When I used Python to insert values into PostgreSQL, I also met the question: column "xxx" does not exist.
The I find the reason in wiki.postgresql:
PostgreSQL uses only single quotes for this (i.e. WHERE name = 'John'). Double quotes are used to quote system identifiers; field names, table names, etc. (i.e. WHERE "last name" = 'Smith').
MySQL uses ` (accent mark or backtick) to quote system identifiers, which is decidedly non-standard.
It means PostgreSQL can use only single quote for field names, table names, etc. So you can not use single quote in value.
My situation is: I want to insert values "the difference of it’s adj for sb and it's adj of sb" into PostgreSQL.
How I figure out this problem:
I replace ' with ’, and I replace " with '. Because PostgreSQL value does not support double quote.
So I think you can use following codes to insert values:
insert into test values (1,'user’s log');
insert into test values (2,'my users');
insert into test values (3,'customer’s');
If you need to get the work done inside Pg:
to_json(value)
https://www.postgresql.org/docs/9.3/static/functions-json.html#FUNCTIONS-JSON-TABLE
You must have to add an extra single quotes -> ' and make doubling quote them up like below examples -> ' ' is the standard way and works of course:
Wrong way: 'user's log'
Right way: 'user''s log'
problem:
insert into test values (1,'user's log');
insert into test values (2,''my users'');
insert into test values (3,'customer's');
Solutions:
insert into test values (1,'user''s log');
insert into test values (2,'''my users''');
insert into test values (3,'customer''s');

Genexus - How to Write String Literals?

We have procedures that initialize our database triggers/functions, so they have the SQL commands inserted on varchar variables as strings in plain code, like the following example:
My questions is:
Is there any way in Genexus to write multiline strings? like c# literal strings using #, or with the recent java 13 text blocks using triple double quotes """ multilineText """
GeneXus currently has no support for multiline.
You are doing it the correct way, based on the code you shared.
You can add a string to a SQL sentence (like this: |) and then do a replace before executing the SQL.
&NewLine = NewLine()
&SQL = &SQL.Replace('|',&newLine())
Or using a regular expression.

Can I format variables like strings in python?

I want to use printing command bellow in many places of my script. But I need to keep replacing "Survived" with some other string.
print(df.Survived.value_counts())
Can I automate the process by formating variable the same way as string? So if I want to replace "Survived" with "different" can I use something like:
var = 'different'
text = 'df.{}.value_counts()'.format(var)
print(text)
unfortunately this prints out "df.different.value_counts()" as as a string, while I need to print the value of df.different.value_counts()
I'm pretty sure alot of IDEs, have this option that is called refactoring, and it allows you to change a similar line of code/string on every line of code to what you need it to be.
I'm aware of VSCode's way of refactoring, is by selecting a part of the code and right click to select the option called change all occurances. This will replace the exact code on every line if it exists.
But if you want to do what you proposed, then eval('df.{}.value_counts()'.format(var)) is an option, but this is very unsecured and dangerous, so a more safer approach would be importing the ast module and using it's literal_eval function which is safer. ast.literal_eval('df.{}.value_counts()'.format(var)).
if ast.literal_eval() doesn't work then try this final solution that works.
def cat():
return 1
text = locals()['df.{}.value_counts'.format(var)]()
Found the way: print(df[var].value_counts())

Python-String to function in 'eval'

I'm trying to build a lisp interpreter in python using 'eval'.
def FUNC(e1,*elements):
print(e1)
eval((input()))
Its working for integers.But is there any way I can use this to input strings?
eg: when I input:
F(a,b,3,5,2)
The above code should print:
a
I don't want to input it as: F('a','b',3,5,2)
Thanks!
The only way to convey a string value is by enclosing it within quote. Other way to do it is by declaring a string variable separately and send it as a parameter instead. However, when you print a string query in interactive command window, it won't be printed with quotes aroun

Resources