SQLite : Insert text with single quote got from a SQL request

六月ゝ 毕业季﹏ 提交于 2019-12-14 04:12:32

问题


I have already check all the forums about this issue and I found a solution for my first insert, I used the "double quoted" instead a single quote as follow:

insertGiftShop(2,"photo02","Modern City by night photo", "item-grumdy1l", "A view of Modern City''s skytrain",1,100, "","no","items",0)

The previous function is inserting my row at the beginning of the game. When I check the database, the value is stored like this : " A view of Modern City's skytrain ".

It works very well! Now I'm trying to get the stored information "A view of Modern City's skytrain" and insert it in another table such as following:

function insertInventory(id, code, name, src, desc, sale, qtyoninventory, price, usetxt, type)
   local sql = "insert into inventory (id, code, name, src, desc, sale, qtyoninventory, price, usetxt, type) values (" .. id.. ",'" .. code .. "','" .. name .. "', '" .. src .. "', '" .. desc .. "', '" .. sale .. "',"..qtyoninventory..","..price..",'"..usetxt.."','"..type.."')"
   db:exec(sql)
end


insertInventory(maxid+1,row_2.code, row_2.name, row_2.src, row_2.desc, "no",1,row_2.price,row_2.usetxt, row_2.type)

In this situation, I'm getting the row_2.desc (what is "A view of etc..") directly from a stored filed. BUT it doesn't work because it takes the "single quote"!

How can I tell "format" the row_2.desc in order to add a needed "double quote" when the text has single quote inside?


Edit:

According to your comment, I've change the way to "insert" data in my tables.

So, I tried this:

tx.executeSql("INSERT INTO inventory(id, code, name) VALUES(?,?,?)",[2, "photo02", "Modern City's skytrain"])

I've an error near "[". Is the syntax correct?

I used this, is it correct and prevent SQL injection?

db:exec([[INSERT INTO items(id, code, name, src, desc, sale, qty, price, usetxt, type, onscene, area) VALUES(1,"ls01","LETP", "item-lss", "LVP","no",0,100, "It this burger?", "items", "yes", "table02")]])

回答1:


Never ever put string values directly into an SQL string! This not only gives you formatting problems (as you have seen), but also allows SQL injection attacks.

Use parameters instead, then you don't need to escape quotes:

tx.executeSql("INSERT INTO MyTable(ID, Name, Description) VALUES(?,?,?)",
              [2, "photo02", "Modern City's skytrain"]);


来源:https://stackoverflow.com/questions/27255538/sqlite-insert-text-with-single-quote-got-from-a-sql-request

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!