0

Here's the problem: if I use { } for the update command like so:

package require sqlite3
fileRepo eval {UPDATE uploads SET $col=$data WHERE rowid=$id}

I cannot substitute any variables inside the curly brackets. it all has to be hard coded.

However, if I use " " for the update command like so:

fileRepo eval "UPDATE uploads SET $col='$data' WHERE rowid=$id"

I can substitute variables inside the double quotes, but I must use ' ' in order to put in data with spaces so sql sees it as one input. If I don't I get an error if I send something like

$data = "Legit Stack"

Because it has a space the sql will choke on the word: Stack unless it is placed within single quotes

Therefore...

If I send this data to the update command:

$col = description
$data = "Stack's Pet"

I get the following error:

near "s": syntax error while executing "fileRepo eval "UPDATE uploads SET $col='$data' WHERE rowid=$id" ...

Thus given these rules I can see no way to pass a single quote or apostrophe to the update command successfully. Is there a different way to do this?

Thanks!

4

2 回答 2

4

While it is true that you can escape the single quotes by doubling them (as usual in SQL), you open up your code to the dangers of SQL injection attacks.

It might be better to split your code into two distinct steps:

  • Substitute with format {UPDATE uploads SET %s=$data WHERE rowid=$id} $col

  • let sqlite3 magic eval turn the $data and $id into bound variables for a prepared statement

This way you only need to sanitize your col variable, to make sure it contains a valid column name and nothing else (should be easy), instead of all your data. In addition, you do not need to copy large values as often, so a two step approach will even be faster. To make it even clearer you want to use a bind variable, try the alternative syntax with a : in front of a variable name.

package require sqlite3
set stmt [format {UPDATE uploads SET %s=:data WHERE rowid=:id} $col]
fileRepo eval $stmt

Recommended Reading:

于 2015-11-03T22:35:18.533 回答
0

You have to use an escape apostrophe. So it should look like this:

$data = "Stack''s Pet"

于 2015-11-03T16:32:02.013 回答