Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
368 views
in Technique[技术] by (71.8m points)

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

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")]])
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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"]);

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...