I'm generating a dynamic sql query based on some user input. Here is the code that prepares the query:
var preparedParamValues = paramValues.map(paramValue => `'${paramValue}'`).join(',');
var sql = `INSERT INTO [DB] (${paramNames}) VALUES (${preparedParamValues})`;
When I send the following string to the DB it throws the below error:
'They're forced to drive stupid cars.'
I get an error :
'Unclosed quotation mark after the character string \')\'.'
I'm trying to find a way to escape all those characters but I don't understand the error or at least the last part of it with all the symbols.
You have to use two single quotes when a single quote appears in the string:
'They''re forced to drive stupid cars.'
Related
So in my node code postgres query is returning double quotes when it's returning its values.
As opposed to the query at pgAdmin.
I already tried to solve it using regex but this attempt was innefective. So if anyone had a problem like this and could help me, I would be glad.
Thanks in advance
There are neither quotes nor extra back slashes in the string. They are part of the string representation as literal.
Try console.log(value) - or even directly console.log('/\\w/g') - and you'll see the output is /\w/g as expected.
To answer my own question, after a lot of reading and researching, I managed to discover that because a backslash character is a special character it will create some problems around its implementation in regex, because it is not permitted to have a lone backslash stored in a variable for example.
This would never work stored inside a variable because the backslash have to be escaped.
/\w+/ig
Javascript will transform it automatically to be able to perform.
/\w+/ig
When reading
RegExp - Javascript documentation, I came across an interesting statement, the RegExp function will recognize and use a double slash regex, thankfully!
So I just adapted my regex to split it's statement from it's flags and mount it again using RegExp.
Below is the code that I used to solve this problem
// Getting values from postgres
const values = (await pgConn.admRead.query(clientQuery)).rows[0].value || [];
// Splitting regex ( values: /\w/g )
const valuesSplit = values.split('/'); // RESULT -> ['', w, g]
// Removing first array item when it's empty
if (valuesSplit[0].length === 0) {
valuesSplit.shift();
}
// Creating regex from splitted array
const regexOperation = new RegExp(valuesSplit[0], valuesSplit[1]);
// Executing replace function
const messageMasked = message.replace(regexOperation, '*');
return messageMasked;
I have a query that looks like this:
INSERT INTO table VALUES ('47677;2019;2019;10T-1001-10010AS;A05;International;TieLineKoman-KosovoB;L_KOM-KOSB;2018;NULL;NULL;;NULL;Tieline;NULL;10XAL-KESH-----J;0;3')
that is produced by parsing a csv file.
The query is not in a valid form, I have to replace all semicolons with the string ',' (comma inside single quotes). What I want to get is:
('47677','2019','2019','10T-1001-10010AS','A05','International','TieLineKoman-KosovoB','L_KOM-KOSB','2018','NULL','NULL','','NULL','Tieline','NULL','10XAL-KESH-----J','0','3')
I have tried to do this in many different ways, but I end up with backshlashes added in my string. This is what I get:
"INSERT INTO AllocatedEICDetail VALUES ('47677\\',\\'2019\\',\\'2019\\',\\'10T-1001-10010AS\\',\\'A05\\',\\'International\\',\\'TieLineKoman-KosovoB\\',\\'L_KOM-KOSB\\',\\'2018\\',\\'NULL\\',\\'NULL\\',\\'\\',\\'NULL\\',\\'Tieline\\',\\'NULL\\',\\'10XAL-KESH-----J\\',\\'0\\',\\'3')"
Any ideas how to do this properly without having the backslashes added?
Thank you!
//the string you have
const string = '47677;2019;2019;10T-1001-10010AS;A05;International;TieLineKoman-KosovoB;L_KOM-KOSB;2018;NULL;NULL;;NULL;Tieline;NULL;10XAL-KESH-----J;0;3';
//the string you need:
const targetString = string.replace(/\;/g,',');
You specify a small regex between the forward slashes in replace which is a simple ';', give it a 'g' flag for global which will replace all instances, and in the second argument supply what you need it replaced with.
I am trying to insert data in my SQL Server and I am using loopback framework in the backend.
But at the time of inserting a string with single quotes, I get an error
RequestError: Unclosed quotation mark after the character string ',8272)
SELECT id AS insertId from #insertedIds
and the string which I am trying to insert is like this
An open-ended equity fund investing in stocks which are currently undervalued to their future earning potential and carry medium risk profile to provide 'Capital Appreciation',
I tried to resolve this issue by replacing single quotes but afterward, when I am selecting data from the database again this error is happening.
Code is something like this
let mutualFundRecord = {
fundObjective: An open-ended equity fund investing in stocks which are currently undervalued to their future earning potential and carry medium risk profile to provide 'Capital Appreciation'
}
function updateRecordData(mutualFundRecord, callback) {
const promise = new Promise(function (resolve, reject) {
let promiseP1;
if (!mutualFundRecord.instrument || !mutualFundRecord.instrument.id) {
promiseP1 = app.models.Instrument.create(mutualFundRecord)
.then(function (newlyCreatedInstrument) {
mutualFundRecord.mutualFundDetails.instrumentId = newlyCreatedInstrument.id;
return app.models.MutualFundDetails.create(mutualFundRecord.mutualFundDetails);
});
}
}
If you try to assign the string with a single quote(s) in it to the variable, you would get the same error as you mentioned in your question:
declare #text nvarchar(100) = 'That's all folks'
Error: Unclosed quotation mark after the character string ''.
What you need to do is to replace each single quote character in the string with two single quote characters - that's called "escaping" the character.
Following code is a small demo and it will show you that although in the code you see two quote character, only one quote will be written into the database:
declare #text nvarchar(100) = 'That''s all folks'
select #text as Txt
into #t
select Txt from #t
That's all folks
I am creating a basic chat application in flutter. It involves a Text Field where the user can enter any text and click on the send button.
The application works fine for any string you enter in the text box except for the string containing quotes. I get a Database exception when trying to add that string to the sql database as the quotes are not escaped.
Doing replaceAll("'", "\'").replaceAll('"', "\'") on a string works as i'm using double quotes in sql queries, but all the double quotes are now single quotes.
Thanks for the help.
Does the database support bind parameters? If not, does the package you are using to talk to the database have a string escape function?
Those will work better than doing it manually, especially since there can be very unsafe stuff in the user input beyond quotes. If you are manually putting together a query string and sending it to the DB it will be open to SQL attacks.
For your immediate question, you are replacing with single quotes in both places. Assuming you can escape quotes by prefixing with a slash it should look like .replaceAll('"', '\\"').
Please look for a more secure way to sanitize user input.
The best and safest way to run queries SQL in Dart is to use the bind parameters.
For example, if you are using sqflite you'll need to pass parameters in a List in this way using the ? as wildcard in the query:
INSERT
int id2 = await txn.rawInsert(
'INSERT INTO Test(name, value, num) VALUES(?, ?, ?)',
['another name', 12345678, 3.1416]);
UPDATE
int count = await database.rawUpdate(
'UPDATE Test SET name = ?, value = ? WHERE name = ?',
['updated name', '9876', 'some name']);
DELETE
count = await database
.rawDelete('DELETE FROM Test WHERE name = ?', ['another name']);
Visual Studio is giving me the following error when I submit and store in the database.
"string must be exactly one character long"
to try to resolve tried this but without success:
cmd.Parameters.Add("#nomeEmpresa", OleDb.OleDbType.Integer).Value = Convert.ToChar(cbxEmpresa.Text)
cmd.Parameters.Add("#nomeContacto", OleDb.OleDbType.Integer).Value = Convert.ToChar(txtNomeContacto.Text)
cmd.Parameters.Add("#apelidoContacto", OleDb.OleDbType.Integer).Value = Convert.ToChar(txtApelidoContacto.Text)
cmd.Parameters.Add("#funcao", OleDb.OleDbType.Integer).Value = Convert.ToChar(txtFuncao.Text)
how can I solve this problem?
If you look at the documentation of Convert.ToChar you could read
Converts the first character of a specified string to a Unicode
character. Namespace: System Assembly: mscorlib (in mscorlib.dll)
Syntax
public static char ToChar( string value )
valueType: System.String
A string of length 1.
That's the reason of your error.
However your code seems to be incorrect. If you want to pass Integer values types by your user to your sql you need to convert your input using something like Int32.TryParse(textbox.text)
Instead if you want to pass string values you need to change your parameter type to SqlDbType.NVarChar.
Convert.ToChar(string) requires that the string only contain a single character. You need to gaurrantee this for each of the strings before you call it, or manually select the first character from the string, or something similar.
Docs for Convert.ToChar(string), throws FormatException "The length of value is not 1."
http://msdn.microsoft.com/en-us/library/5f3ew98y(v=vs.110).aspx